package com.yixun.qfbao.api.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.beust.jcommander.internal.Lists;
import com.yixun.common.page.Page;
import com.yixun.common.page.PageUtil;
import com.yixun.qfbao.api.service.*;
import com.yixun.qfbao.apidto.PremisesRecommenderDto;
import com.yixun.qfbao.apidto.*;
import com.yixun.qfbao.apidto.base.CommonReqDTO;
import com.yixun.qfbao.apidto.v10dto.BaseResponseDto;
import com.yixun.qfbao.apidto.v10dto.PremisesPageResponse;
import com.yixun.qfbao.constant.RedisKeyConstant;
import com.yixun.qfbao.convert.PremisesSimpleConvert;
import com.yixun.qfbao.dao.OtherCompanyDao;
import com.yixun.qfbao.mapper.AreaMapper;
import com.yixun.qfbao.mapper.ChannelRoleMapper;
import com.yixun.qfbao.mapper.DistributionAuditMapper;
import com.yixun.qfbao.mapper.PremisesImageMapper;
import com.yixun.qfbao.model.Dictionary;
import com.yixun.qfbao.model.*;
import com.yixun.qfbao.model.dto.*;
import com.yixun.qfbao.model.enums.*;
import com.yixun.qfbao.service.AreaService;
import com.yixun.qfbao.service.BaseCodeValueService;
import com.yixun.qfbao.service.CompanyRelationService;
import com.yixun.qfbao.service.CompanyService;
import com.yixun.qfbao.service.*;
import com.yixun.qfbao.util.ChineseCharToEn;
import com.yixun.qfbao.util.ExceptionMsg;
import com.yixun.qfbao.util.ParseUtils;
import com.yixun.qfbao.util.QiNiuUtil;
import com.yixun.qfbao.util.RedisUtil;
import com.yixun.qfbao.util.StringUtil;
import com.yixun.qfbao.util.exception.TServerException;
import com.yixun.qfbao.xf.mapper.ApartmentLayoutDiagramMapper;
import com.yixun.qfbao.xf.mapper.CustomerPremisesMapper;
import com.yixun.qfbao.xf.mapper.PremisesDynamicMapper;
import com.yixun.qfbao.xf.mapper.PremisesMapper;
import com.yixun.qfbao.xf.model.ApartmentLayoutDiagram;
import com.yixun.qfbao.xf.model.CaseMember;
import com.yixun.qfbao.xf.model.Premises;
import com.yixun.qfbao.xf.model.PremisesDynamic;
import com.yixun.qfbao.xf.model.dto.*;
import com.yixun.qfbao.xf.model.enums.*;
import com.yixun.qfbao.xf.service.*;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.jdbc.UncategorizedSQLException;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;

/**
 * [文件名称]<br>
 * PremisesServiceImpl.java<br>
 * <br>
 * [文件描述]<br>
 * 楼盘接口<br>
 * <br>
 *
 * @author jzliu
 * @version 1.00
 */
@Service
public class PremisesApiServiceImpl implements PremisesApiService {

	private static final Logger logger = LoggerFactory.getLogger(PremisesApiServiceImpl.class);

	@Autowired
	private CaseMemberService caseMemberService;

	@Autowired
	private PremisesService premisesService;

	@Autowired
	private CompanyService companyService;

	@Autowired
	private PartnerInfoService partnerInfoService;

	@Autowired
	private PremisesRelationService premisesRelationService;

	@Autowired
	private CompanyRelationService companyRelationService;

	@Autowired
	private ApartmentLayoutDiagramService apartmentLayoutDiagramService;
	@Autowired
	private PremisesMapper premisesMapper;
	@Autowired
	private PremisesImageService premisesImageService;

	@Autowired
	private PremisesDynamicService premisesDynamicService;

	@Autowired
	private AreaService areaService;

	@Autowired
	private BaseCodeValueService baseCodeValueService;

	@Autowired
	private DictionaryService dictionaryService;

	@Autowired
	private CustomerPremisesService customerPremisesService;

	@Autowired
	private DistributionAuditMapper distributionAuditMapper;

	@Autowired
	private PremisesImageMapper premisesImageMapper;

	@Autowired
	private V10BindService v10BindService;

	@Autowired
	private OtherCompanyDao otherCompanyDao;

	@Autowired
	private PremisesRelationExternalService premisesRelationExternalService;

	@Autowired
	private PremisesDynamicExternalService premisesDynamicExternalService;

	@Autowired
	private CustomerPremisesMapper customerPremisesMapper;

	@Value("${system.domain}")
	private  String domainName;
	@Autowired
	private WxTemplateMsgService wxTemplateMsgService;

	@Autowired
	private DecisionConfigService decisionConfigService;

	@Autowired
	private PremisesRecommenderService premisesRecommenderService;

	@Autowired
	private EstateAdviserService estateAdviserService;
	@Autowired
	private AreaMapper areaMapper;
	
	@Autowired
	PremisesPartnerService premisesPartnerService;
	
	@Autowired
	ApartmentLayoutDiagramMapper apartmentLayoutDiagramMapper;
	
	@Autowired
	ChannelRoleMapper channelRoleMapper;
	
	@Autowired
	PremisesDynamicMapper premisesDynamicMapper;
	
	@Autowired
	DataPermissionService dataPermissionService;


	/**
	 * （2） 驻守楼盘列表
	 *
	 * @param reqDto
	 * @return
	 */
	@Override
	public GetCaseMemberListResDto getCaseMemberList(GetCaseMemberListReqDto reqDto) {
		GetCaseMemberListResDto resDto = new GetCaseMemberListResDto();

		List<CaseMemberDto> list = new ArrayList<>();
		PartnerInfo partner = partnerInfoService.selectById(stringToLong(reqDto.getUserId()));
		if (null != partner) {
			// 是否是管理员(0是 1否)
			if (!"0".equals(partner.getAccountType())) {
				CaseMemberDto entity = new CaseMemberDto();
				entity.setPremisesStatus(PremisesStatusEnum.type1.getNo());
				entity.setCompanyId(partner.getHigherid());
				entity.setPartnerId(partner.getId());
				if(StringUtils.isNotEmpty(reqDto.getNotSaleStatus())){
					entity.setNotSaleStatus(reqDto.getNotSaleStatus());
				}
				entity.setPreStatus(reqDto.getSaleStatus());
				entity.setPremisesSaleStatusList(reqDto.getPremisesSaleStatusList());
				entity.setPremisesName(reqDto.getPremisesName());

				list = caseMemberService.selectPremisesListByDto(entity);
			} else {
				PremisesDto entity = new PremisesDto();
				entity.setCompanyId(partner.getHigherid());
				entity.setPremisesStatus(PremisesStatusEnum.type1.getNo());
				if(StringUtils.isNotEmpty(reqDto.getNotSaleStatus())){
					entity.setNotSaleStatus(reqDto.getNotSaleStatus());
				}
                entity.setListSaleStatus(reqDto.getPremisesSaleStatusList());
				entity.setSaleStatus(reqDto.getSaleStatus());
				entity.setName(reqDto.getPremisesName());
				List<Premises> pl = premisesService.selectListForCaseMember(entity);
				for (Premises pr : pl) {
					CaseMemberDto cm = new CaseMemberDto();
					cm.setPremisesId(pr.getId());
					cm.setPremisesName(pr.getName());
					cm.setSpecialTime(pr.getSpecialTime());
					cm.setSpecialTimeType(pr.getSpecialTimeType());
					cm.setProtectTime(pr.getVisitProtect());
					cm.setProtectTimeType(pr.getVisitProtectType());
                    cm.setReportProtect(pr.getReportProtect());
                    cm.setReportProtectType(pr.getReportProtectType());
					cm.setVisitProtectSwitch(pr.getVisitProtectSwitch());
					cm.setReportWay(pr.getReportWay());
					list.add(cm);
				}
			}
            //当前登录人是否为楼盘项目总监或项目经理
            PremisesDto premisesDto = new PremisesDto();
            premisesDto.setMobileTemp(partner.getPhone());
            premisesDto.setPremisesStatus(PremisesStatusEnum.type1.getNo());
            premisesDto.setCompanyId(partner.getHigherid());
            if(StringUtils.isNotEmpty(reqDto.getNotSaleStatus())){
            	premisesDto.setNotSaleStatus(reqDto.getNotSaleStatus());
			}
			premisesDto.setListSaleStatus(reqDto.getPremisesSaleStatusList());
			premisesDto.setName(reqDto.getPremisesName());
            List<Premises> premisesList = premisesService.selectIdListByMobileTemp(premisesDto);
            if(premisesList != null && premisesList.size() > 0) {
                for (Premises premises : premisesList) {
                    CaseMemberDto cm = new CaseMemberDto();
                    cm.setPremisesId(premises.getId());
                    cm.setPremisesName(premises.getName());
                    cm.setSpecialTime(premises.getSpecialTime());
                    cm.setSpecialTimeType(premises.getSpecialTimeType());
                    cm.setProtectTime(premises.getVisitProtect());
                    cm.setProtectTimeType(premises.getVisitProtectType());
                    cm.setReportProtect(premises.getReportProtect());
                    cm.setReportProtectType(premises.getReportProtectType());
                    cm.setVisitProtectSwitch(premises.getVisitProtectSwitch());
					cm.setReportWay(premises.getReportWay());
                    list.add(cm);
                }
            }

			// 置业顾问关联的楼盘
			if(SystemIdEnum.ASSISTANT.getCode().equals(reqDto.getLoginType())){
				// 只有案场助手需要展示置业顾问报备关联的楼盘
				List<EstateAdviser> adviserList = estateAdviserService.selectListByPartner(partner.getId());
				if(CollectionUtils.isNotEmpty(adviserList)){
					List<Long> premisesIds = adviserList.stream().map(EstateAdviser::getPremisesId).collect(Collectors.toList());
					premisesDto = new PremisesDto();
					premisesDto.setPremisesIds(premisesIds);
					premisesDto.setListSaleStatus(reqDto.getPremisesSaleStatusList());
					premisesDto.setName(reqDto.getPremisesName());
					if(StringUtils.isNotEmpty(reqDto.getNotSaleStatus())){
						premisesDto.setNotSaleStatus(reqDto.getNotSaleStatus());
					}
					premisesDto.setPremisesStatus(PremisesStatusEnum.type1.getNo());
					List<Premises> adviserPremisesList = premisesService.selectIdListByDto(premisesDto);
					if(CollectionUtils.isNotEmpty(adviserPremisesList)) {
						for (Premises premises : adviserPremisesList) {
							CaseMemberDto cm = new CaseMemberDto();
							cm.setPremisesId(premises.getId());
							cm.setPremisesName(premises.getName());
							cm.setSpecialTime(premises.getSpecialTime());
							cm.setSpecialTimeType(premises.getSpecialTimeType());
							cm.setProtectTime(premises.getVisitProtect());
							cm.setProtectTimeType(premises.getVisitProtectType());
							cm.setReportProtect(premises.getReportProtect());
							cm.setReportProtectType(premises.getReportProtectType());
							cm.setVisitProtectSwitch(premises.getVisitProtectSwitch());
							cm.setReportWay(premises.getReportWay());
							list.add(cm);
						}
					}
				}
			}
		}

		List<Map<String, String>> caseMemberList = new ArrayList<>();
		if(null != list && list.size() > 0) {
            List<CaseMemberDto> distinctList = list.stream().filter(distinctByKey(CaseMemberDto::getPremisesId)).collect(Collectors.toList());
            for (CaseMemberDto cm : distinctList) {
                Map<String, String> map = new HashMap<>();
                map.put("premisesId", cm.getPremisesId().toString());
                map.put("premisesName", cm.getPremisesName());
                map.put("specialTime", StringUtils.isEmpty(cm.getSpecialTime())?"0":cm.getSpecialTime());
                // 历史数据可能无值，默认取分钟-3
                map.put("specialTimeType", StringUtils.isEmpty(cm.getSpecialTimeType())?"3":cm.getSpecialTimeType());
                map.put("protectTime", StringUtils.isEmpty(cm.getProtectTime())?"0":cm.getProtectTime());
                map.put("protectTimeType", StringUtils.isEmpty(cm.getProtectTimeType())?"0":cm.getProtectTimeType());
                map.put("reportProtect", cm.getReportProtect() == null?"0":cm.getReportProtect().toString());
                map.put("reportProtectType", cm.getReportProtectType() == null?"0":cm.getReportProtectType().toString());
                map.put("visitProtectSwitch", cm.getVisitProtectSwitch()+"");
				map.put("reportWay", cm.getReportWay());
                caseMemberList.add(map);
            }
        }


		resDto.setCaseMemberList(caseMemberList);
		resDto.setResult(ResultEnum.SUCCESS.getNo());
		return resDto;
	}

    /**
     * 过滤器
     * @param keyExtractor
     * @param <T>
     * @return
     */
    public static <T> Predicate<T> distinctByKey(Function<? super T, Object> keyExtractor) {
        Map<Object, Boolean> seen = new ConcurrentHashMap<>();
        return object -> seen.putIfAbsent(keyExtractor.apply(object), Boolean.TRUE) == null;
    }


	/**
	 * （3） 获取项目
	 *
	 * @param reqDto
	 * @return
	 */
	@Override
	public GetPremisesListResDto getPremisesList(GetPremisesListReqDto reqDto) {
		GetPremisesListResDto resDto = new GetPremisesListResDto();

		// 通过userId获取对应楼盘ID
		CaseMemberDto caseMemberDto = new CaseMemberDto();
		caseMemberDto.setPartnerId(stringToLong(reqDto.getUserId()));
		List<CaseMember> list = caseMemberService.selectListByDto(caseMemberDto);
		if (list == null) {
			resDto.setResult(ResultEnum.FAIL.getNo());
			resDto.setResultMsg("获取项目失败!");
			return resDto;
		}
		List<Long> premisesIds = new ArrayList<Long>();
		for (CaseMember cm : list) {
			premisesIds.add(cm.getPremisesId());
		}
		// 获取楼盘信息
		PremisesDto premisesDto = new PremisesDto();
		premisesDto.setPremisesIds(premisesIds);
		premisesDto.setPremisesStatus(reqDto.getPremisesStatus());
		premisesDto.setSaleStatus(reqDto.getSaleStatus());
		List<Premises> premisesList = premisesService.selectListByDto(premisesDto);
		if (premisesList == null) {
			resDto.setResult(ResultEnum.FAIL.getNo());
			resDto.setResultMsg("获取项目失败!");
			return resDto;
		}
		List<Map<String, String>> pList = new ArrayList<Map<String, String>>();
		for (Premises pre : premisesList) {
			Map<String, String> map = new HashMap<String, String>(16);
			map.put("premisesId", pre.getId().toString());
			map.put("premisesName", pre.getName());
			pList.add(map);
		}

		resDto.setPremisesList(pList);
		resDto.setResult(ResultEnum.SUCCESS.getNo());
		return resDto;
	}

	/**
	 * （4） 楼盘列表
	 *
	 * @param reqDto
	 * @return
	 */
	@Override
	public GetAgentPremisesPageResDto getAgentPremisesPage(GetAgentPremisesPageReqDto reqDto) {
		GetAgentPremisesPageResDto resDto = new GetAgentPremisesPageResDto();
		int pageNo = reqDto.getPageNo();
		int pageSize = reqDto.getPageSize();

		String domain = reqDto.getDomain();
        String companyUuid=reqDto.getCompanyUuid();
        if (StringUtils.isEmpty(domain) && StringUtils.isEmpty(companyUuid)){
        	resDto.setResult(ResultEnum.FAIL.getNo());
        	resDto.setResultMsg("公司信息获取失败!");
            return resDto;
        }

        // 根据域名或者公司uuid查询开发商
		CompanyDto cDto = new CompanyDto();
	    cDto.setDomain(domain);
	    cDto.setStatus(CheckStatusEnum.SUCCESS.getNo());
	    cDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
	    cDto.setCompanyUuid(companyUuid);
	    Company company = companyService.selectByDto(cDto);

	    if (null == company) {
            //此处为商户不存在
	    	resDto.setResult(ResultEnum.FAIL.getNo());
	    	resDto.setResultMsg("未获取到开发商信息!");
            return resDto;
        }
		
	    Long companyId = company.getId();
		// 查询合作机构
		PartnerInfo pi = partnerInfoService.selectById(stringToLong(reqDto.getUserId()));
		if (pi == null) {
			resDto.setResult(ResultEnum.FAIL.getNo());
			resDto.setResultMsg("未获取到合作机构!");
			return resDto;
		}
		PremisesDto entity = new PremisesDto();
		//传入的公司ID，游客所属的公司ID
		if (pi.getUserRoleId() != null && pi.getUserRoleId() == -1) {
			entity.setCompanyId(companyId);
		} else {
			//总代公司ID
			// 在楼盘关系表中查询相关楼盘
			PremisesRelationDto relationDto = new PremisesRelationDto();
			relationDto.setDevCompanyId(companyId);
			relationDto.setAgentCompanyId(pi.getHigherid());
			relationDto.setStatus(MechanismStatusEnum.enable.getNo());
			relationDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
			List<PremisesRelation> relation = premisesRelationService.selectListByDto(relationDto);
			if (relation == null) {
				resDto.setResult(ResultEnum.FAIL.getNo());
				resDto.setResultMsg("在楼盘关系表中查询相关楼盘失败!");
				return resDto;
			}
			List<Long> premisesIds = new ArrayList<Long>();
			for (PremisesRelation pre : relation) {
				premisesIds.add(pre.getPremisesId());
			}
			// 当有楼盘id时才设置进去
			if (premisesIds.size() > 0) {
				entity.setPremisesIds(premisesIds);
			} else {
				// 没有楼盘时设置成-1
				premisesIds.add(-1L);
				entity.setPremisesIds(premisesIds);
			}
		}
		if (StringUtils.isNotBlank(reqDto.getName())) {
			entity.setName(reqDto.getName());
		}
		if (reqDto.getProvinceId() != null) {
			entity.setProvinceId(reqDto.getProvinceId());
		}
		if (reqDto.getCityId() != null) {
			entity.setCityId(reqDto.getCityId());
		}
		if (reqDto.getAreaId() != null) {
			entity.setAreaId(reqDto.getAreaId());
		}
		if (StringUtils.isNotBlank(reqDto.getEstateType())) {
			entity.setEstateType(reqDto.getEstateType());
		}
		entity.setPremisesStatus(PremisesStatusEnum.type1.getNo());
		// 在售状态
		entity.setSaleStatus(SaleStatusEnum.type_1.getNo());
		entity.setOrders(
				"CASE WHEN t.main_push = 1 THEN NULL ELSE t.main_push END desc, CASE WHEN t.sequence IS NULL THEN 1 ELSE 0 END ASC," +
                "t.sequence ASC,t.main_push_settime desc, t.premises_status asc,t.create_time desc ");
		String averagePrice = reqDto.getAveragePrice();
		if (StringUtils.isNotBlank(averagePrice)) {
			// 避免查询条件混淆
			entity.setAveragePrice(null);
			if (averagePrice.contains("<=")) {
				entity.setSufAveragePrice(Long.valueOf(averagePrice.substring(2)));
			}
			if (averagePrice.contains(">")) {
				entity.setPreAveragePrice(Long.valueOf(averagePrice.substring(1)));
			}
			if (averagePrice.contains("-")) {
				String[] averagePriceArr = averagePrice.split("-");
				entity.setPreAveragePrice(Long.valueOf(averagePriceArr[0]));
				entity.setSufAveragePrice(Long.valueOf(averagePriceArr[1]));
			}
		}

		String acreage = reqDto.getAcreage();
		if (StringUtils.isNotBlank(acreage)) {
			if (acreage.contains("<=")) {
				entity.setSufAcreage(Long.valueOf(acreage.substring(2)));
			}
			if (acreage.contains(">")) {
				entity.setPreAcreage(Long.valueOf(acreage.substring(1)));
			}
			if (acreage.contains("-")) {
				String[] acreageArr = acreage.split("-");
				entity.setPreAcreage(Long.valueOf(acreageArr[0]));
				entity.setSufAcreage(Long.valueOf(acreageArr[1]));
			}
		}
		if (reqDto.getCityId() != null && reqDto.getCityId() != 0) {
			entity.setCityId(reqDto.getCityId());
		}
		
		Page<PremisesDto> page = new Page<>();
		// update by zilong.liu 
		if(SystemIdEnum.WEAPP_AGENCY.getCode().equals(reqDto.getLoginType())) {
			Integer minPrice = reqDto.getMinPrice();
			Integer maxPrice = reqDto.getMaxPrice();
			Integer priceEnumNumber = reqDto.getPriceEnumNumber();
			
			String roomNumbers = reqDto.getRoomNumbers();
			
			Integer minArea = reqDto.getMinArea();
			Integer maxArea = reqDto.getMaxArea();
			List<Integer> areaNumbers = reqDto.getAreaEnumNumbers();
			if(roomNumbers != null || minPrice != null || maxPrice != null || priceEnumNumber != null
					|| minArea != null || maxArea != null || (areaNumbers != null && areaNumbers.size() != 0)) {
				ApartmentLayoutDiagramDto apartmentLayoutDiagramDto  = new ApartmentLayoutDiagramDto ();
				apartmentLayoutDiagramDto.setPremisesIds(entity.getPremisesIds());
				// 无室的时候需要进行单独处理
				if(HuxingEnum.HU_XING_0.getNo().equals(roomNumbers)) {
					apartmentLayoutDiagramDto.setWeappApartmentLayout(roomNumbers);
				}else {
					int minRoom = HuxingEnum.getMinByNo(roomNumbers);
					int maxRoom = HuxingEnum.getMaxByNo(roomNumbers);
					if(minRoom != -1 && maxRoom != -1) {
						apartmentLayoutDiagramDto.setMinRoom(minRoom);
						apartmentLayoutDiagramDto.setMaxRoom(maxRoom);
					} 
				}
				List<ApartmentLayoutDiagram> apartmentLayoutDiagrams = apartmentLayoutDiagramMapper.selectListByDto(apartmentLayoutDiagramDto);
				List<Long> premisesIds = new ArrayList<>();
				premisesIds.add(-1L);
				for (ApartmentLayoutDiagram apartmentLayoutDiagram : apartmentLayoutDiagrams) {
					boolean priceInRangeFlag = true;
					if(minPrice == null && maxPrice != null) {
						minPrice = 0;
						priceInRangeFlag = apartmentLayoutDiagram.judgeTotalPriceInRange(minPrice, maxPrice);
						minPrice = null;
					}else if(minPrice != null && maxPrice == null) {
						maxPrice = Integer.MAX_VALUE;
						priceInRangeFlag = apartmentLayoutDiagram.judgeTotalPriceInRange(minPrice, maxPrice);
						maxPrice = null;
					}else if(minPrice != null && maxPrice != null) {
						priceInRangeFlag = apartmentLayoutDiagram.judgeTotalPriceInRange(minPrice, maxPrice);
					}else if(priceEnumNumber != null) {
						int[] minAndMaxValue = PriceEnum.getMinAndMaxValueByNumber(priceEnumNumber);
						if(minAndMaxValue != null) {
							minPrice = minAndMaxValue[0];
							maxPrice = minAndMaxValue[1];
							priceInRangeFlag = apartmentLayoutDiagram.judgeTotalPriceInRange(minPrice, maxPrice);
						}
					}
					
					if(!priceInRangeFlag) {
						continue;
					}
					
					boolean areaInRangeFlag = true;
					if(minArea == null && maxArea != null) {
						minArea = 0;
						areaInRangeFlag = apartmentLayoutDiagram.judgeAreaInRange(minArea, maxArea);
						minArea = null;
					}else if(minArea != null && maxArea == null) {
						maxArea = Integer.MAX_VALUE;
						areaInRangeFlag = apartmentLayoutDiagram.judgeAreaInRange(minArea, maxArea);
						maxArea = null;
					}else if(minArea != null && maxArea != null) {
						areaInRangeFlag = apartmentLayoutDiagram.judgeAreaInRange(minArea, maxArea);
					}else if(areaNumbers != null) {
						areaInRangeFlag = apartmentLayoutDiagram.judgeAreaInRange(areaNumbers);
					}
					Long premisesId = apartmentLayoutDiagram.getPremisesId();
					if( priceInRangeFlag && areaInRangeFlag) {
							premisesIds.add(premisesId);
					}
				}
				entity.setPremisesIds(premisesIds);
			}
			entity.setPartnerId(Long.parseLong(reqDto.getUserId()));
			entity.setMainPush(reqDto.getMainPushStatus());
			// 标签
			entity.setCodes(reqDto.getCodes());
			// 装修情况
			entity.setDecorationTypes(reqDto.getDecorationTypes());
			//销售状态
			List<Integer> saleStatus = reqDto.getSaleStatus();
			if(saleStatus == null || saleStatus.size() == 0) {
				saleStatus = new ArrayList<>();
				saleStatus.add(Integer.parseInt(SaleStatusValidEnum.type_0.getNo()));
				saleStatus.add(Integer.parseInt(SaleStatusValidEnum.type_1.getNo()));
			}
			entity.setSaleStatusList(saleStatus);
			if(AttetionStatusEnum.set_attetion.getNo() == reqDto.getAttetionStatus()) {
				entity.setRelType(RelTypeEnum.attention.getNo());
				entity.setRelFlag(AttetionStatusEnum.set_attetion.getNo());
			}
			Integer relType = reqDto.getRelType();
			if(relType != null) {
				entity.setRelType(relType);
				entity.setRelFlag(AttetionStatusEnum.set_attetion.getNo());
			}
			//用途
			entity.setSql(PremisesOriginEnum.getByNo(reqDto.getPremisesOrigin()) == null? null: 
				PremisesOriginEnum.getByNo(reqDto.getPremisesOrigin()).getExtraSql());
			page = premisesService.getPremisesIncludeAttetion(entity, PageUtil.begin(pageNo, pageSize), pageSize);
		}else {
			page = premisesService.getPageModelByAcreage(entity, PageUtil.begin(pageNo, pageSize), pageSize);
			// 经纪人对应各楼盘所推荐的客户数量
			List<CustomerPremisesDto> cpDtoList = null;
			CustomerPremisesDto cpDto = new CustomerPremisesDto();
			cpDto.setStaffId(Long.valueOf(reqDto.getUserId()));
			cpDto.setStaffCompanyId(pi.getHigherid());
			cpDtoList = customerPremisesService.selectAdminRecommendCusByPremises(cpDto);
			Map<String, String> map = new HashMap<>();
			if (null != cpDtoList) {
				for (CustomerPremisesDto returnCpDto : cpDtoList) {
					String premisesId = String.valueOf(returnCpDto.getPremisesId());
					String key = premisesId;
					String value = "0";
					if (null != returnCpDto.getReportCount()) {
						value = String.valueOf(returnCpDto.getReportCount());
					}
					map.put(key, value);
				}
			}
			List<PremisesDto> premisesList = page.getRows();
			if (null != premisesList && premisesList.size() > 0) {
				for (PremisesDto premises : premisesList) {
					String key = String.valueOf(premises.getId());
					String value = "0";
					if (StringUtils.isNotBlank(map.get(key))) {
						value = map.get(key);
					}
					premises.setReportCount(value);

					// 从楼盘中获取佣金、带看奖、结佣方式
					String commission = premises.getCommission();
					String reward = premises.getReward();
					String way = premises.getCommissionWay();
					premises.setCommission(commission);
					premises.setReward(reward);
					if (StringUtils.isNotBlank(way) && !"0".equals(way)) {
						premises.setCommissionWay(CommissionWayEnum.getDescByNo(way));
					} else {
						// 可能采用新增合作机构的结佣方式，但是之前的楼盘结佣方式有影响
						premises.setCommissionWay("");
					}
				}
			}
		}
		
		resDto.setGetAgentPremisesPage(page);
		resDto.setResult(ResultEnum.SUCCESS.getNo());
		resDto.setResultMsg(ResultEnum.SUCCESS.getDes());
		return resDto;
	}

	/**
	 * 歷史報備樓盤
	 * @param reqDto
	 * @return
	 */
	@Override
	public GetAgentPremisesPageResDto getAgentPremisesHistoryPage(GetAgentPremisesPageReqDto reqDto) {
		GetAgentPremisesPageResDto resDto = new GetAgentPremisesPageResDto();

		int pageNo = reqDto.getPageNo();
		int pageSize = reqDto.getPageSize();

		String domain = reqDto.getDomain();
		String companyUuid=reqDto.getCompanyUuid();
		if (StringUtils.isEmpty(domain) && StringUtils.isEmpty(companyUuid)){
			resDto.setResult(ResultEnum.FAIL.getNo());
			resDto.setResultMsg("公司信息获取失败!");
			return resDto;
		}

		// 根据域名或者公司uuid查询开发商
		CompanyDto cDto = new CompanyDto();
		cDto.setDomain(domain);
		cDto.setStatus(CheckStatusEnum.SUCCESS.getNo());
		cDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
		cDto.setCompanyUuid(companyUuid);
		Company company = companyService.selectByDto(cDto);

		if (null == company) {
			//此处为商户不存在
			resDto.setResult(ResultEnum.FAIL.getNo());
			resDto.setResultMsg("未获取到开发商信息!");
			return resDto;
		}
		Long companyId = company.getId();


		// 查询合作机构
		PartnerInfo pi = partnerInfoService.selectById(stringToLong(reqDto.getUserId()));
		if (pi == null) {
			resDto.setResult(ResultEnum.FAIL.getNo());
			resDto.setResultMsg("未获取到合作机构!");
			return resDto;
		}

		PremisesDto entity = new PremisesDto();
		if (pi.getUserRoleId() != null && pi.getUserRoleId() == -1) {
			entity.setCompanyId(companyId);
		} else {
			// 在楼盘关系表中查询相关楼盘
			PremisesRelationDto relationDto = new PremisesRelationDto();
			relationDto.setDevCompanyId(companyId);
			relationDto.setAgentCompanyId(pi.getHigherid());
			relationDto.setStatus(MechanismStatusEnum.enable.getNo());
			relationDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
			List<PremisesRelation> relation = premisesRelationService.selectListByDto(relationDto);
			if (relation == null) {
				resDto.setResult(ResultEnum.FAIL.getNo());
				resDto.setResultMsg("在楼盘关系表中查询相关楼盘失败!");
				return resDto;
			}
			List<Long> premisesIds = new ArrayList<Long>();
			for (PremisesRelation pre : relation) {
				premisesIds.add(pre.getPremisesId());
			}
			// 当有楼盘id时才设置进去
			if (premisesIds.size() > 0) {
				entity.setPremisesIds(premisesIds);
			} else {
				// 没有楼盘时设置成-1
				premisesIds.add(-1L);
				entity.setPremisesIds(premisesIds);
			}
		}
		if (StringUtils.isNotBlank(reqDto.getName())) {
			entity.setName(reqDto.getName());
		}
		if (reqDto.getProvinceId() != null) {
			entity.setProvinceId(reqDto.getProvinceId());
		}
		if (reqDto.getCityId() != null) {
			entity.setCityId(reqDto.getCityId());
		}
		if (reqDto.getAreaId() != null) {
			entity.setAreaId(reqDto.getAreaId());
		}
		if (StringUtils.isNotBlank(reqDto.getEstateType())) {
			entity.setEstateType(reqDto.getEstateType());
		}
		entity.setPremisesStatus(PremisesStatusEnum.type1.getNo());
		// 在售状态
		entity.setSaleStatus(SaleStatusEnum.type_1.getNo());
		entity.setOrders(
				"CASE WHEN t.main_push = 1 THEN NULL ELSE t.main_push END desc, CASE WHEN t.sequence IS NULL THEN 1 ELSE 0 END ASC," +
						"t.sequence ASC,t.main_push_settime desc, t.premises_status asc,t.create_time desc ");
		String averagePrice = reqDto.getAveragePrice();
		if (StringUtils.isNotBlank(averagePrice)) {
			// 避免查询条件混淆
			entity.setAveragePrice(null);
			if (averagePrice.contains("<=")) {
				entity.setSufAveragePrice(Long.valueOf(averagePrice.substring(2)));
			}
			if (averagePrice.contains(">")) {
				entity.setPreAveragePrice(Long.valueOf(averagePrice.substring(1)));
			}
			if (averagePrice.contains("-")) {
				String[] averagePriceArr = averagePrice.split("-");
				entity.setPreAveragePrice(Long.valueOf(averagePriceArr[0]));
				entity.setSufAveragePrice(Long.valueOf(averagePriceArr[1]));
			}
		}

		String acreage = reqDto.getAcreage();
		if (StringUtils.isNotBlank(acreage)) {
			if (acreage.contains("<=")) {
				entity.setSufAcreage(Long.valueOf(acreage.substring(2)));
			}
			if (acreage.contains(">")) {
				entity.setPreAcreage(Long.valueOf(acreage.substring(1)));
			}
			if (acreage.contains("-")) {
				String[] acreageArr = acreage.split("-");
				entity.setPreAcreage(Long.valueOf(acreageArr[0]));
				entity.setSufAcreage(Long.valueOf(acreageArr[1]));
			}
		}
		if (reqDto.getCityId() != null && reqDto.getCityId() != 0) {
			entity.setCityId(reqDto.getCityId());
		}

		entity.setStaffId(stringToLong(reqDto.getUserId()));

		Page<PremisesDto> page = premisesService.getPageModelForHistory(entity, PageUtil.begin(pageNo, pageSize), pageSize);



		// 经纪人对应各楼盘所推荐的客户数量
		List<CustomerPremisesDto> cpDtoList = null;
		CustomerPremisesDto cpDto = new CustomerPremisesDto();
		cpDto.setStaffId(Long.valueOf(reqDto.getUserId()));
		cpDto.setStaffCompanyId(pi.getHigherid());
		cpDtoList = customerPremisesService.selectAdminRecommendCusByPremises(cpDto);

		Map<String, String> map = new HashMap<>();
		if (null != cpDtoList) {
			for (CustomerPremisesDto returnCpDto : cpDtoList) {
				String premisesId = String.valueOf(returnCpDto.getPremisesId());
				String key = premisesId;
				String value = "0";
				if (null != returnCpDto.getReportCount()) {
					value = String.valueOf(returnCpDto.getReportCount());
				}
				map.put(key, value);
			}
		}

		List<PremisesDto> premisesList = page.getRows();
		if (null != premisesList && premisesList.size() > 0) {
			for (PremisesDto premises : premisesList) {
				String key = String.valueOf(premises.getId());
				String value = "0";
				if (StringUtils.isNotBlank(map.get(key))) {
					value = map.get(key);
				}
				premises.setReportCount(value);

				// 从楼盘中获取佣金、带看奖、结佣方式
				String commission = premises.getCommission();
				String reward = premises.getReward();
				String way = premises.getCommissionWay();
				premises.setCommission(commission);
				premises.setReward(reward);
				if (StringUtils.isNotBlank(way) && !"0".equals(way)) {
					premises.setCommissionWay(CommissionWayEnum.getDescByNo(way));
				} else {
					// 可能采用新增合作机构的结佣方式，但是之前的楼盘结佣方式有影响
					premises.setCommissionWay("");
				}

			}
		}

		resDto.setGetAgentPremisesPage(page);
		resDto.setResult(ResultEnum.SUCCESS.getNo());
		return resDto;
	}

	/**
	 * （5） 获取存在规则的项目
	 *
	 * @param reqDto
	 * @return
	 */
	@Override
	public GetPremisesWithCRResDto getPremisesWithCR(GetPremisesWithCRReqDto reqDto) {
		GetPremisesWithCRResDto resDto = new GetPremisesWithCRResDto();

		// 查询合作机构
		PartnerInfo pi = partnerInfoService.selectById(stringToLong(reqDto.getUserId()));
		if (pi == null) {
			resDto.setResult(ResultEnum.FAIL.getNo());
			resDto.setResultMsg("未获取到合作机构!");
			return resDto;
		}

		PremisesDto premisesDto = new PremisesDto();
		premisesDto.setCompanyId(pi.getHigherid());
		Map<String, Object> reMap = premisesService.getPremisesList(premisesDto);

		resDto.setPremisesList(reMap);
		resDto.setResult(ResultEnum.SUCCESS.getNo());
		return resDto;
	}

	/**
	 * （6） 驻守楼盘分页
	 *
	 * @param reqDto
	 * @return
	 */
	@Override
	public GetCaseMemberPageResDto getCaseMemberPage(GetCaseMemberPageReqDto reqDto) {
		GetCaseMemberPageResDto resDto = new GetCaseMemberPageResDto();
		resDto.setResult(ResultEnum.SUCCESS.getNo());

		PartnerInfo pi = partnerInfoService.selectById(stringToLong(reqDto.getUserId()));
		if (pi == null) {
			resDto.setResult(ResultEnum.FAIL.getNo());
			resDto.setResultMsg("未获取到合作机构!");
			return resDto;
		}
		int pageNo = reqDto.getPageNo();
		int pageSize = reqDto.getPageSize();
		String name = reqDto.getName();
		Long provinceId = reqDto.getProvinceId();
		Long cityId = reqDto.getCityId();
		Long areaId = reqDto.getAreaId();
		String premisesStatus = reqDto.getPremisesStatus();
		PremisesDto dto = new PremisesDto();
		dto.setCompanyId(pi.getHigherid());
		dto.setProvinceId(provinceId);
		dto.setCityId(cityId);
		dto.setAreaId(areaId);
		dto.setPremisesStatus(premisesStatus);
		dto.setListSaleStatus(reqDto.getPremisesSaleStatus());
		String accountType = pi.getAccountType();
		if (MechanismAccountTypeEnum.individual.getNo().equals(accountType)) {
			dto.setPartnerId(pi.getId());
		}
		dto.setName(name);
		//项目总监或者项目经理可查看楼盘
		dto.setMobileTemp(pi.getPhone());
		dto.setOrders("orderStatus, al.create_time desc");
		Page<Premises> premisesPage = premisesService.findPremisesByPartnerModel(dto, PageUtil.begin(pageNo, pageSize), pageSize);
		List<Premises> premisesList = premisesPage.getRows();
		List<PremisesSimpleDto> psDtoList = new ArrayList<>();
		if(CollectionUtils.isNotEmpty(premisesList)){
			List<Long> ids = new ArrayList<>();
			List<Long> provinceIds = premisesList.stream().map(Premises::getProvinceId).collect(Collectors.toList());
			List<Long> cityIds = premisesList.stream().map(Premises::getCityId).collect(Collectors.toList());
			List<Long> areaIds = premisesList.stream().map(Premises::getAreaId).collect(Collectors.toList());
			ids.addAll(provinceIds);
			ids.addAll(cityIds);
			ids.addAll(areaIds);
			AreaDto areaDto = new AreaDto();
			areaDto.setIds(ids);
			List<Area> areaList = areaService.selectListByDto(areaDto);
			Map<Long, Area> areaMap = areaList.stream().collect(Collectors.toMap(Area::getId, Function.identity()));
			psDtoList = premisesList.stream()
					.map(item -> PremisesSimpleConvert.convertPremises2SimpleDto(item, areaMap))
					.collect(Collectors.toList());
		}

		Page<PremisesSimpleDto> data = new Page<>();
		data.setTotal(premisesPage.getTotal());
		data.setPageSize(premisesPage.getPageSize());
		data.setTotalPages(premisesPage.getTotalPages());
		data.setPageNumber(premisesPage.getPageNumber());
		data.setRows(psDtoList);
		resDto.setData(data);
		resDto.setResult(ResultEnum.SUCCESS.getNo());
		return resDto;
	}

	/**
	 * （8） 经纪人已驻守楼盘
	 *
	 * @param reqDto
	 * @return
	 */
	@Override
	public GetBindPremisesResDto getBindPremises(GetPartnerBindPremisesReqDto reqDto) {
		GetBindPremisesResDto resDto = new GetBindPremisesResDto();
		List<Premises> premisesList = new ArrayList<>();
		// 通过userId获取对应楼盘ID
		CaseMemberDto caseMemberDto = new CaseMemberDto();
		caseMemberDto.setPartnerId(reqDto.getPartnerId());
		List<CaseMember> cmList = caseMemberService.selectListByDto(caseMemberDto);
		if (CollectionUtils.isEmpty(cmList) || Objects.isNull(reqDto.getPartnerId())) {
			resDto.setResult(ResultEnum.SUCCESS.getNo());
			resDto.setInPremisesList(null);
			return resDto;
		}
		List<Long> premisesIds = new ArrayList<>();
		for (CaseMember cm : cmList) {
			premisesIds.add(cm.getPremisesId());
		}
		if(CollectionUtils.isEmpty(premisesIds)){
            resDto.setResult(ResultEnum.SUCCESS.getNo());
            resDto.setInPremisesList(null);
            return resDto;
        }

		PremisesDto entity = new PremisesDto();
		entity.setPremisesIds(premisesIds);
		entity.setName(reqDto.getPremisesName());
		entity.setPremisesStatus(reqDto.getPremisesStatus());
		entity.setSaleStatus(reqDto.getSaleStatus());
		entity.setProvinceId(reqDto.getProvince());
		entity.setCityId(reqDto.getCity());
		entity.setAreaId(reqDto.getArea());
		entity.setOrders(" orderStatus, t.create_time desc");
		premisesList = premisesService.getListByCaseMember(entity);
		if(CollectionUtils.isEmpty(premisesList)){
			resDto.setInPremisesList(null);
			return resDto;
		}

		// 查询楼盘关联关系
		Set<Long> areaIds = new HashSet<Long>();
		if (null != premisesList && premisesList.size() > 0) {
			for (Premises p : premisesList) {
				areaIds.add(p.getProvinceId());
				areaIds.add(p.getCityId());
				areaIds.add(p.getAreaId());
			}
		}
		// 查询城区，公司
		Map<Long, Area> areaMap = new HashMap<Long, Area>();
		List<Area> areas = areaMapper.selectWithIds(areaIds);
		if (areas != null && areas.size() > 0) {
			areaMap = areas.stream().collect(Collectors.toMap(Area::getId, a -> a, (k1, k2) -> k1));
		}

		List<PremisesDto> premisesListNew = new ArrayList<>();
		for(Premises premises: premisesList){
			PremisesDto premisesDto = new PremisesDto();
			BeanUtils.copyProperties(premises, premisesDto);
			if(Objects.nonNull(premises.getProvinceId()) && Objects.nonNull(areaMap.get(premises.getProvinceId()))){
				premisesDto.setProvinceName(areaMap.get(premises.getProvinceId()).getName());
			}
			if(Objects.nonNull(premises.getProvinceId()) && Objects.nonNull(areaMap.get(premises.getCityId()))){
				premisesDto.setCityName(areaMap.get(premises.getCityId()).getName());
			}
			if(Objects.nonNull(premises.getProvinceId()) && Objects.nonNull(areaMap.get(premises.getAreaId()))){
				premisesDto.setAreaName(areaMap.get(premises.getAreaId()).getName());
			}
			premisesListNew.add(premisesDto);
		}
		resDto.setInPremisesList(premisesListNew);
		return resDto;
	}

	/**
	 * （8） 经纪人未驻守楼盘
	 *
	 * @param reqDto
	 * @return
	 */
	@Override
	public GetPartnerUnBindPremisesResDto getPartnerUnBindPremises(GetPartnerBindPremisesReqDto reqDto) {
		GetPartnerUnBindPremisesResDto resDto = new GetPartnerUnBindPremisesResDto();

		PartnerInfo pi = partnerInfoService.selectById(Long.valueOf(reqDto.getUserId()));
		if (pi == null || Objects.isNull(reqDto.getPartnerId())) {
			resDto.setResult(ResultEnum.FAIL.getNo());
			resDto.setResultMsg("未找到用户信息");
			return resDto;
		}

		// 通过userId获取对应楼盘ID
		CaseMemberDto caseMemberDto = new CaseMemberDto();
		caseMemberDto.setPartnerId(reqDto.getPartnerId());
		List<CaseMember> list = caseMemberService.selectListByDto(caseMemberDto);
		List<Long> premisesIds = new ArrayList<Long>();
		if (CollectionUtils.isNotEmpty(list)) {
			for (CaseMember cm : list) {
				premisesIds.add(cm.getPremisesId());
			}
		}

		PremisesDto entity = new PremisesDto();
		entity.setUnPremisesIds(premisesIds);
		entity.setCompanyId(pi.getHigherid());

		entity.setName(reqDto.getPremisesName());
		entity.setPremisesStatus(reqDto.getPremisesStatus());
		entity.setSaleStatus(reqDto.getSaleStatus());
		entity.setProvinceId(reqDto.getProvince());
		entity.setCityId(reqDto.getCity());
		entity.setAreaId(reqDto.getArea());
		entity.setOrders(" orderStatus, t.create_time desc");
		List<Premises> premisesList = premisesService.getListByCaseMember(entity);
		if(CollectionUtils.isEmpty(premisesList)){
			resDto.setOutPremisesList(null);
			return resDto;
		}

		// 查询楼盘关联关系
		Set<Long> areaIds = new HashSet<Long>();
		if (null != premisesList && premisesList.size() > 0) {
			for (Premises p : premisesList) {
				areaIds.add(p.getProvinceId());
				areaIds.add(p.getCityId());
				areaIds.add(p.getAreaId());
			}
		}
		// 查询城区，公司
		Map<Long, Area> areaMap = new HashMap<Long, Area>();
		List<Area> areas = areaMapper.selectWithIds(areaIds);
		if (areas != null && areas.size() > 0) {
			areaMap = areas.stream().collect(Collectors.toMap(Area::getId, a -> a, (k1, k2) -> k1));
		}
		List<PremisesDto> premisesListNew = new ArrayList<>();
		for(Premises premises: premisesList){
			PremisesDto premisesDto = new PremisesDto();
			BeanUtils.copyProperties(premises, premisesDto);
			if(Objects.nonNull(premises.getProvinceId()) && Objects.nonNull(areaMap.get(premises.getProvinceId()))){
				premisesDto.setProvinceName(areaMap.get(premises.getProvinceId()).getName());
			}
			if(Objects.nonNull(premises.getProvinceId()) && Objects.nonNull(areaMap.get(premises.getCityId()))){
				premisesDto.setCityName(areaMap.get(premises.getCityId()).getName());
			}
			if(Objects.nonNull(premises.getProvinceId()) && Objects.nonNull(areaMap.get(premises.getAreaId()))){
				premisesDto.setAreaName(areaMap.get(premises.getAreaId()).getName());
			}
			premisesListNew.add(premisesDto);
		}
		resDto.setOutPremisesList(premisesListNew);
		return resDto;
	}

	/**
	 * （10） 经纪人驻守楼盘
	 *
	 * @param reqDto
	 * @return
	 */
	@Transactional(rollbackFor = Exception.class)
	@Override
	public BindPartnerToPremisesResDto bindPartnerToPremises(BindPartnerToPremisesReqDto reqDto) {
		BindPartnerToPremisesResDto resDto = new BindPartnerToPremisesResDto();
		List<String> premisesIds= null;
		if (StringUtils.isNotBlank(reqDto.getPremisesIds())) {
			// 楼盘Id
			premisesIds = Arrays.asList(reqDto.getPremisesIds().split(","));
		}

		String domain = reqDto.getDomain();
        String companyUuid=reqDto.getCompanyUuid();
        String loginType = reqDto.getLoginType();
        if (StringUtils.isEmpty(domain) && StringUtils.isEmpty(companyUuid)) {
        	resDto.setResult(ResultEnum.FAIL.getNo());
        	resDto.setResultMsg("获取公司信息失败!");
            return resDto;
        }

        CompanyDto cDto = new CompanyDto();
        cDto.setDomain(domain);
        cDto.setStatus(CheckStatusEnum.SUCCESS.getNo());
        cDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
        cDto.setCompanyUuid(companyUuid);
        Company company = companyService.selectByDto(cDto);
        if (null == company) {
            //根据域名查找商户,此处为商户不存在
        	resDto.setResult(ResultEnum.FAIL.getNo());
            if (loginType.equals(SystemIdEnum.AGENCY_WEB.getCode())
                    || loginType.equals(SystemIdEnum.AGENCY_h5.getCode())) {
            	resDto.setResultMsg("您与该开发商无合作关系!");
            }
            resDto.setResultMsg("用户不存在或已被禁用!");
            return resDto;
        }

		// 清除此用户的楼盘权限
		String redisKey = RedisKeyConstant.Permission.DEV_USER_PREMISES_PERMISSION + reqDto.getPartnerId();
		RedisUtil.delete(redisKey);

		Long companyId = company.getId();
		//取消所有的驻守楼盘
		if(premisesIds == null){
			CaseMemberDto caseMemberDto = new CaseMemberDto();
			if(reqDto.getPartnerId() == null){
				resDto.setResult(ResultEnum.FAIL.getNo());
				resDto.setResultMsg("人员信息不为空");
				return resDto;
			}
			caseMemberDto.setPartnerId(reqDto.getPartnerId());
			List<CaseMember> caseMemberList = caseMemberService.selectListByDto(caseMemberDto);
			if(CollectionUtils.isNotEmpty(caseMemberList)){
				caseMemberList.forEach(item -> {
					CaseMemberDto delCasememberDto = new CaseMemberDto();
					delCasememberDto.setId(item.getId());
					delCasememberDto.setDelFlag(DelFlagEnum.DEL.getNo());
					caseMemberService.update(delCasememberDto);
				});
			}
			resDto.setResult(ResultEnum.SUCCESS.getNo());
			return resDto;
		}

		// 删除已经绑定的
		CaseMemberDto entity = new CaseMemberDto();
		entity.setPartnerId(reqDto.getPartnerId());
		List<CaseMember> caseMember = caseMemberService.selectListByDto(entity);
		Map<Long,CaseMember> caseMemberMap = caseMember.stream().collect(Collectors.toMap(CaseMember::getPremisesId,CaseMember -> CaseMember, (oldValue, newValue) -> newValue));

		for(CaseMember member : caseMember){
			boolean add = true;
			for(String premisesId : premisesIds){
				if(Long.valueOf(premisesId).equals(member.getPremisesId())){
					add = false;
					break;
				}
			}
			if(add){
				CaseMemberDto caseMemberDto = new CaseMemberDto();
				caseMemberDto.setId(member.getId());
				caseMemberDto.setDelFlag(DelFlagEnum.DEL.getNo());
				caseMemberService.update(caseMemberDto);
			}
		}


		// 添加新驻守楼盘
		if(premisesIds != null && premisesIds.size() > 0){
			for (String id : premisesIds) {
				long premiseId = Long.parseLong(id);
				//不存在的驻守信息
				if(!caseMemberMap.containsKey(premiseId)){
					//添加楼盘
					// 获取楼盘信息
					Premises premises = premisesService.selectSimpleById(premiseId);
					if (null != premises && DelFlagEnum.DEL.getNo().equals(premises.getDelFlag())) {
						continue;
					}

					entity = new CaseMemberDto();
					entity.setPartnerId(reqDto.getPartnerId());
					entity.setPremisesId(premiseId);
					entity.setPremisesName(premises.getName());
					entity.setCompanyId(companyId);
					entity.setSmsStatus("1");
					entity.setDelFlag(DelFlagEnum.UNDEL.getNo());
					caseMemberService.create(entity);
				}
			}
		}

		resDto.setResult(ResultEnum.SUCCESS.getNo());
		return resDto;
	}

	/**
	 * （11） 新增楼盘
	 *
	 * @param reqDto
	 * @return
	 */
	@Transactional(rollbackFor = Exception.class)
	@Override
	public AddOrEditPremisesResDto addPremises(AddOrEditPremisesReqDto reqDto) {
		AddOrEditPremisesResDto resDto = new AddOrEditPremisesResDto();
		try {
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			String domain = reqDto.getDomain();
	        String companyUuid=reqDto.getCompanyUuid();
	        if (StringUtils.isEmpty(domain) && StringUtils.isEmpty(companyUuid)) {
	        	resDto.setResult(ResultEnum.FAIL.getNo());
	        	resDto.setResultMsg("获取公司信息失败!");
	            return resDto;
	        }

	        // 根据域名或者公司uuid查询开发商
			CompanyDto cDto = new CompanyDto();
		    cDto.setDomain(domain);
		    cDto.setStatus(CheckStatusEnum.SUCCESS.getNo());
		    cDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
		    cDto.setCompanyUuid(companyUuid);
		    Company company = companyService.selectByDto(cDto);

		    if (null == company) {
	            //此处为商户不存在
		    	resDto.setResult(ResultEnum.FAIL.getNo());
		    	resDto.setResultMsg("未获取到开发商信息!");
	            return resDto;
	        }
			Long companyId = company.getId();
			PremisesDto entity = new PremisesDto();
			BeanUtils.copyProperties(reqDto, entity);
			entity.setCompanyId(companyId);
			entity.setPremisesStatus(PremisesStatusEnum.type0.getNo());
			entity.setFromSource(FromSourceEnum.FIRST.getNo());
			// 开盘日期
			if (StringUtils.isNotBlank(reqDto.getOpeningDate())) {
				entity.setOpeningTime(sdf.parse(reqDto.getOpeningDate()));
			}
			// 入住日期
			if (StringUtils.isNotBlank(reqDto.getCheckInDate())) {
				entity.setCheckInTime(sdf.parse(reqDto.getCheckInDate()));
			}
			// 合作开始有效期
			if (StringUtils.isNotBlank(reqDto.getCooperationBeginDate())) {
				entity.setCooperationBeginTime(sdf.parse(reqDto.getCooperationBeginDate()));
			}
			// 合作结束有效期
			if (StringUtils.isNotBlank(reqDto.getCooperationEndDate())) {
				entity.setCooperationEndTime(sdf.parse(reqDto.getCooperationEndDate()));
			}
			if (StringUtils.isEmpty(entity.getSaveDays())) {
				entity.setSaveDays("7");
			}
			PremisesDto premisesDto = premisesService.create(entity);
			if (premisesDto == null) {
				resDto.setResult(ResultEnum.FAIL.getNo());
				resDto.setResultMsg("新增楼盘失败!");
				return resDto;
			}
			// 向楼盘关系表中绑定经纪人和楼盘关系
			insertPremisesRelation(premisesDto);

			// 将创建楼盘经纪人绑定到楼盘上
			bindUserToNewPremises(premisesDto, Long.valueOf(reqDto.getUserId()));

			// 保存可售户型
			String hxtInfo = reqDto.getHxtInfo();
			if (StringUtils.isBlank(hxtInfo)) {
				resDto.setResult(ResultEnum.SUCCESS.getNo());
				return resDto;
			}
			// 1、先删除原数据，再进行保存
			ApartmentLayoutDiagramDto diagramDto = new ApartmentLayoutDiagramDto();
			diagramDto.setPremisesId(premisesDto.getId());
			try {
				apartmentLayoutDiagramService.delete(diagramDto);
			}catch (Exception e){
				logger.error("ApartmentLayoutDiagramDto delete error：{}", e);
				resDto.setResult(ResultEnum.FAIL.getNo());
				resDto.setResultMsg("新增楼盘失败!");
				return resDto;
			}
			// 2、解析户型json，保存数据
			JSONArray array = JSONArray.parseArray(hxtInfo);
			for (int i = 0; i < array.size(); i++) {
				JSONObject jsonObj = JSONObject.parseObject(array.get(i).toString());
				diagramDto.setArea(jsonObj.getString("area"));
				diagramDto.setApartmentLayout(jsonObj.getString("apartmentLayout"));
				diagramDto.setUrl(jsonObj.getString("url"));
				diagramDto.setOrientations(jsonObj.getString("orientations"));
				diagramDto.setAveragePrice(jsonObj.getString("averagePrice"));
				diagramDto.setHuxingName(jsonObj.getString("huxingName"));
				diagramDto.setHouseStruct(jsonObj.getString("houseStruct"));
				diagramDto.setDecoration(jsonObj.getString("decoration"));
				diagramDto.setToDelete(jsonObj.getString("toDelete"));
				apartmentLayoutDiagramService.create(diagramDto);
			}
			// 新增楼盘相册
			List<PremisesImage> premisesImageList = JSONArray.parseArray(reqDto.getPremisesImages(),
					PremisesImage.class);
			if (premisesImageList != null && premisesImageList.size() > 0) {
				premisesImageService.adds(premisesImageList, premisesDto.getId());
			}

			// 回传户型信息
			ApartmentLayoutDiagramDto aldDto = new ApartmentLayoutDiagramDto();
			aldDto.setPremisesId(premisesDto.getId());
			List<ApartmentLayoutDiagram> aldList = apartmentLayoutDiagramService.selectListByDto(aldDto);
			for (ApartmentLayoutDiagram ad : aldList) {
				ad.setAprtmentInfo(getApartments(ad.getApartmentLayout()));
			}
			resDto.setImgList(aldList);

			// 新增证照
			List<PremisesImage> premisesLicenseImagesList = JSONArray.parseArray(reqDto.getLicenseImages(),
					PremisesImage.class);
			if (premisesLicenseImagesList != null && !premisesLicenseImagesList.isEmpty()) {
				premisesImageService.adds(premisesLicenseImagesList, premisesDto.getId());
			}
			// 添加到访时间逾期决策配置
			AddOverdueDecisionConfig config = reqDto.getVisitOverdueData();
			if(Objects.nonNull(config) && Objects.nonNull(config.getDecisionService())){
				decisionConfigService.addOverdueDecisionConfig(premisesDto.getId(),reqDto.getUserId(), config);
			}
			//添加交易时间逾期决策配置
			config = reqDto.getDealOverdueData();
			if(Objects.nonNull(config)  && Objects.nonNull(config.getDecisionService())){
				decisionConfigService.addOverdueDecisionConfig(premisesDto.getId(),reqDto.getUserId(), config);
			}
			resDto.setPremisesId(premisesDto.getId());
			resDto.setResult(ResultEnum.SUCCESS.getNo());
		} catch (Exception e) {
			logger.error("新增楼盘失败: {}", e);

			if(e instanceof  UncategorizedSQLException){
				resDto.setResult(ResultEnum.FAIL.getNo());
				String resultMsg = ExceptionMsg.getPremisesException(((UncategorizedSQLException) e).getSQLException());
				if(StringUtils.isNotEmpty(resultMsg)){
					resDto.setResultMsg(resultMsg);
				}else{
					resDto.setResultMsg("新增楼盘失败!");
				}
			}else{
				resDto.setResult(ResultEnum.FAIL.getNo());
				resDto.setResultMsg("新增楼盘失败!");
			}
		}
		return resDto;
	}

	/**
	 * 绑定合作的经纪公司和楼盘
	 *
	 * @param premisesDto
	 */
	private void insertPremisesRelation(PremisesDto premisesDto) {
		CompanyRelationDto dto = new CompanyRelationDto();
		dto.setDevCompany(premisesDto.getCompanyId());
		dto.setDelFlag(DelFlagEnum.UNDEL.getNo());
		List<CompanyRelationDto> list = companyRelationService.selectDtoListByDto(dto);
		for (CompanyRelationDto relation : list) {
			PremisesRelationDto relationDto = new PremisesRelationDto();
			relationDto.setDevCompanyId(premisesDto.getCompanyId());
			relationDto.setAgentCompanyId(relation.getAgentCompany());
			relationDto.setStatus(MechanismStatusEnum.enable.getNo());
			relationDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
			relationDto.setPremisesId(premisesDto.getId());
			premisesRelationService.create(relationDto);
		}
	}

	private void bindUserToNewPremises(PremisesDto premisesDto, Long userId){
		// 1、判断用户是否需要添加
		if(Objects.nonNull(userId)){
			PartnerInfo partnerInfo = partnerInfoService.selectById(userId);
			if(MechanismAccountTypeEnum.individual.getNo().equals(partnerInfo.getAccountType())){
                // 清除缓存
                String redisKey = RedisKeyConstant.Permission.DEV_USER_PREMISES_PERMISSION + userId;
                RedisUtil.delete(redisKey);
				// 2、为员工添加驻场getAgencyIndexSwitch
				CaseMemberDto caseMemberDto = new CaseMemberDto();
				caseMemberDto.setPremisesId(premisesDto.getId());
				caseMemberDto.setPartnerId(userId);
				CaseMember caseMember = caseMemberService.selectByDto(caseMemberDto);
				if(Objects.isNull(caseMember)){
					caseMemberDto.setPremisesName(premisesDto.getName());
					caseMemberDto.setCompanyId(premisesDto.getCompanyId());
					caseMemberDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
					caseMemberService.create(caseMemberDto);
				}
			}
		}
	}

	/**
	 * （12）楼盘修改
	 *
	 * @param reqDto
	 * @return
	 */
	@Transactional(rollbackFor = Exception.class)
	@Override
	public AddOrEditPremisesResDto editPremises(AddOrEditPremisesReqDto reqDto) {
		AddOrEditPremisesResDto resDto = new AddOrEditPremisesResDto();
		try {
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			if (reqDto.getId() == null) {
				resDto.setResult(ResultEnum.FAIL.getNo());
				resDto.setResultMsg("楼盘ID为空!");
				return resDto;
			}

			String domain = reqDto.getDomain();
	        String companyUuid=reqDto.getCompanyUuid();
	        String loginType = reqDto.getLoginType();
	        if (StringUtils.isEmpty(domain) && StringUtils.isEmpty(companyUuid)) {
	        	resDto.setResult(ResultEnum.FAIL.getNo());
	        	resDto.setResultMsg("获取公司信息失败!");
	            return resDto;
	        }

	        CompanyDto cDto = new CompanyDto();
	        cDto.setDomain(domain);
	        cDto.setStatus(CheckStatusEnum.SUCCESS.getNo());
	        cDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
	        cDto.setCompanyUuid(companyUuid);
	        Company company = companyService.selectByDto(cDto);
	        if (null == company) {
	            //根据域名查找商户,此处为商户不存在
	        	resDto.setResult(ResultEnum.FAIL.getNo());
	            if (loginType.equals(SystemIdEnum.AGENCY_WEB.getCode())
	                    || loginType.equals(SystemIdEnum.AGENCY_h5.getCode())) {
	            	resDto.setResultMsg("您与该开发商无合作关系!");
	            }
	            resDto.setResultMsg("用户不存在或已被禁用!");
	            return resDto;
	        }

	        Long companyId=company.getId();


			Premises nowPremises = premisesService.selectById(reqDto.getId());
            PremisesDto entity = new PremisesDto();
            // 原始数据拷贝
            BeanUtils.copyProperties(nowPremises, entity);
            // 修改数据覆盖
            BeanUtils.copyProperties(reqDto, entity);
            entity.setCompanyId(companyId);
			if (null != nowPremises && nowPremises.getPremisesStatus().equals(PremisesStatusEnum.type2.getNo())) {
				entity.setPremisesStatus(PremisesStatusEnum.type0.getNo());
			}
			// 编辑楼盘,楼盘下架
			entity.setShelvesStatus(0L);

			// 开盘日期
			if (StringUtils.isNotBlank(reqDto.getOpeningDate())) {
				entity.setOpeningTime(sdf.parse(reqDto.getOpeningDate()));
			}
			// 入住日期
			if (StringUtils.isNotBlank(reqDto.getCheckInDate())) {
				entity.setCheckInTime(sdf.parse(reqDto.getCheckInDate()));
			}
			// 合作开始有效期
			if (StringUtils.isNotBlank(reqDto.getCooperationBeginDate())) {
				entity.setCooperationBeginTime(sdf.parse(reqDto.getCooperationBeginDate()));
			}
			// 合作结束有效期
			if (StringUtils.isNotBlank(reqDto.getCooperationEndDate())) {
				entity.setCooperationEndTime(sdf.parse(reqDto.getCooperationEndDate()));
			}
			// 查看楼盘审核状态
			if (null != nowPremises && nowPremises.getPremisesStatus().equals(PremisesStatusEnum.type1.getNo())) {
				entity.setPremisesStatus(PremisesStatusEnum.type0.getNo());
			}
			if(entity.getReportProtectType() != null && entity.getReportProtectType().equals(4L)){
				entity.setReportProtect(null);
			}
			int updateRow = premisesService.updateByPrimaryKey(entity);
			if (updateRow < 0) {
				resDto.setResult(ResultEnum.FAIL.getNo());
				resDto.setResultMsg("修改楼盘失败!");
				return resDto;
			}

			// 保存可售户型
			String hxtInfo = reqDto.getHxtInfo();
			if (StringUtils.isBlank(hxtInfo)) {
				resDto.setResult(ResultEnum.SUCCESS.getNo());
				return resDto;
			}
			// 1、先删除原数据，再进行保存
			// ApartmentLayoutDiagramDto diagramDto = new ApartmentLayoutDiagramDto();
			// diagramDto.setPremisesId(entity.getId());l
			// apartmentLayoutDiagramService.destroy(diagramDto);
			List<ApartmentLayoutDiagramDto> apartmentLayoutDiagramDtoList = new ArrayList<ApartmentLayoutDiagramDto>();
			// 2、解析户型json，保存数据
			JSONArray array = JSONArray.parseArray(hxtInfo);
			for (int i = 0; i < array.size(); i++) {
				ApartmentLayoutDiagramDto diagramDto = new ApartmentLayoutDiagramDto();
				JSONObject jsonObj = JSONObject.parseObject(array.get(i).toString());
				diagramDto.setId(
						StringUtils.isBlank(jsonObj.getString("id")) ? null : Long.parseLong(jsonObj.getString("id")));
				diagramDto.setPremisesId(entity.getId());
				diagramDto.setArea(jsonObj.getString("area"));
				diagramDto.setApartmentLayout(jsonObj.getString("apartmentLayout"));
				diagramDto.setUrl(jsonObj.getString("url"));
				diagramDto.setOrientations(jsonObj.getString("orientations"));
                diagramDto.setAveragePrice(jsonObj.getString("averagePrice"));
				diagramDto.setHuxingName(jsonObj.getString("huxingName"));
				diagramDto.setHouseStruct(jsonObj.getString("houseStruct"));
				diagramDto.setDecoration(jsonObj.getString("decoration"));
				diagramDto.setToDelete(jsonObj.getString("toDelete"));
				apartmentLayoutDiagramDtoList.add(diagramDto);
			}
			apartmentLayoutDiagramService.editList(apartmentLayoutDiagramDtoList);

			// 回传户型信息
			ApartmentLayoutDiagramDto aldDto = new ApartmentLayoutDiagramDto();
			aldDto.setPremisesId(reqDto.getId());
			List<ApartmentLayoutDiagram> aldList = apartmentLayoutDiagramService.selectListByDto(aldDto);
			for (ApartmentLayoutDiagram ad : aldList) {
				ad.setAprtmentInfo(getApartments(ad.getApartmentLayout()));
			}
			resDto.setImgList(aldList);

			// 证照文件
			List<PremisesImage> premisesLicenseImages = JSONArray.parseArray(reqDto.getLicenseImages(),
					PremisesImage.class);
			if(premisesLicenseImages != null && premisesLicenseImages.size() > 0) {
			    premisesImageService.edits(premisesLicenseImages,reqDto.getId());
            }
			// 编辑楼盘相册
			// JSONArray arrayImg = JSONArray.parseArray(reqDto.getPremisesImages());
			List<PremisesImage> premisesImageList = JSONArray.parseArray(reqDto.getPremisesImages(),
					PremisesImage.class);
			if(premisesImageList != null && premisesImageList.size() > 0) {
			    premisesImageService.edits(premisesImageList,reqDto.getId());
            }

			PremisesRelationExternalDto preDTO = new PremisesRelationExternalDto();
			preDTO.setSysId(ExternalSysEnum.V10.getCode());
			preDTO.setIsDeleted(DelFlagEnum.UNDEL.getNo());
			preDTO.setPremisesId(nowPremises.getId());
			List<PremisesRelationExternal> list = premisesRelationExternalService.selectListByDto(preDTO);
			// 判断是否需要推给v10
			if (list != null && list.size() > 0) {
				List<BaseResponseDto> responseList = v10BindService.issueFirsthandEstate(nowPremises,list, "0");
			}

			// 发送下架微信模板消息
            if(PremisesStatusEnum.type1.getNo().equals(nowPremises.getPremisesStatus())
                    && SaleStatusEnum.type_1.getNo().equals(nowPremises.getPremisesStatus())
                    && PremisesStatusEnum.type0.getNo().equals(entity.getPremisesStatus())) {
                sendWeixinMsgWithPremises(reqDto.getAgencyAccessToken(),reqDto.getCompanyUuid(),reqDto.getDomain()
                    ,reqDto.getId().toString(),nowPremises.getSaleStatus(),nowPremises.getSaleStatus(),entity.getPremisesStatus());
            }

            resDto.setPremisesId(reqDto.getId());
			resDto.setResult(ResultEnum.SUCCESS.getNo());
		} catch (Exception e) {
			logger.error("修改楼盘失败: {}", e);
			if(e instanceof UncategorizedSQLException){
				resDto.setResult(ResultEnum.FAIL.getNo());
				String resultMsg = ExceptionMsg.getPremisesException(((UncategorizedSQLException) e).getSQLException());
				if(StringUtils.isNotEmpty(resultMsg)){
					resDto.setResultMsg(resultMsg);
				}else{
					resDto.setResultMsg("修改楼盘失败!");
				}
			}else{
				resDto.setResult(ResultEnum.FAIL.getNo());
				resDto.setResultMsg("修改楼盘失败!");
			}

		}
		return resDto;
	}

	/**
	 * （13）楼盘审核
	 *
	 * @param reqDto
	 * @return
	 */
	@Override
	@Transactional
	public AuditPremisesResDto auditPremises(AuditPremisesReqDto reqDto) {
		AuditPremisesResDto resDto = new AuditPremisesResDto();
        // 获取楼盘信息
        Premises premises = premisesService.selectById(reqDto.getId());

		PremisesDto entity = new PremisesDto();
		entity.setId(reqDto.getId());
		entity.setPremisesStatus(reqDto.getPremisesStatus());
		entity.setRemark(reqDto.getRemark());
		entity.setCommissionWay("");
		entity.setReward("");
		entity.setCommission("");
		entity.setCommissionRate("");
		int updateRow = premisesService.audit(entity);
		if (updateRow < 0) {
			resDto.setResult(ResultEnum.FAIL.getNo());
			resDto.setResultMsg("楼盘审核失败!");
			return resDto;
		}

		 String domain = reqDto.getDomain();
	     String companyUuid=reqDto.getCompanyUuid();
	     String loginType = reqDto.getLoginType();
	     if (StringUtils.isEmpty(domain) && StringUtils.isEmpty(companyUuid)) {
	    	 resDto.setResult(ResultEnum.FAIL.getNo());
	    	 resDto.setResultMsg("获取公司信息失败!");
	         return resDto;
	     }


        CompanyDto cDto = new CompanyDto();
        cDto.setDomain(domain);
        cDto.setStatus(CheckStatusEnum.SUCCESS.getNo());
        cDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
        cDto.setCompanyUuid(companyUuid);
        Company company = companyService.selectByDto(cDto);
        if (null == company) {
            //根据域名查找商户,此处为商户不存在
        	resDto.setResult(ResultEnum.FAIL.getNo());
            if (loginType.equals(SystemIdEnum.AGENCY_WEB.getCode())
                    || loginType.equals(SystemIdEnum.AGENCY_h5.getCode())) {
            	resDto.setResultMsg("您与该开发商无合作关系!");
            }
            resDto.setResultMsg("用户不存在或已被禁用!");
            return resDto;
        }


        Long devCompanyId=company.getId();
		// 楼盘审核通过之后 同步到V10
		OtherCompany otherCompany = null;
		if (PremisesStatusEnum.type1.getNo().equals(reqDto.getPremisesStatus())) {
			// 判断是否同步v10
			if (devCompanyId == null) {
				// resDto.setResultMsg("未查询到公司id");
				resDto.setResult(ResultEnum.SUCCESS.getNo());
				return resDto;
			}

			List<OtherCompany> listOtherCompany = otherCompanyDao.getV10CompanyListByCompanyId(devCompanyId);
			if (listOtherCompany == null || listOtherCompany.size() == 0) {
				resDto.setResult(ResultEnum.SUCCESS.getNo());
				return resDto;
			}
			otherCompany = listOtherCompany.get(0);

			if (otherCompany == null || otherCompany.getCompanyUuid() == null) {
				resDto.setResultMsg("未查询到公司id");
				resDto.setResult(ResultEnum.SUCCESS.getNo());
				return resDto;
			}
			//获取对接人信息
			CaseMemberDto caseMemberDto = new CaseMemberDto();
			caseMemberDto.setPhoneStatus("1");
			caseMemberDto.setPremisesId(reqDto.getId());
			List<CaseMember> caseMemberList = caseMemberService.selectListByDto(caseMemberDto);
			if(caseMemberList != null && caseMemberList.size() > 0){
				PartnerInfo partnerInfo = partnerInfoService.selectById(caseMemberList.get(0).getPartnerId());
				premises.setManager(partnerInfo.getAccountName());
				premises.setMobile(partnerInfo.getPhone());
			}
			List<BaseResponseDto> listResponse = v10BindService.saveFirsthandEstate(premises, listOtherCompany);

		}
		// 审核不通过
		if (PremisesStatusEnum.type2.getNo().equals(reqDto.getPremisesStatus())) {
			// 获取所需推送状态的楼盘
			PremisesRelationExternalDto preDTO = new PremisesRelationExternalDto();
			preDTO.setSysId(ExternalSysEnum.V10.getCode());
			preDTO.setIsDeleted(DelFlagEnum.UNDEL.getNo());
			preDTO.setPremisesId(premises.getId());
			List<PremisesRelationExternal> list = premisesRelationExternalService.selectListByDto(preDTO);
			if (list != null && list.size() > 0) {
				List<BaseResponseDto> responseList = v10BindService.issueFirsthandEstate(premises,list, reqDto.getPremisesStatus());
			}
		}
		// 清除缓存
		if(StringUtils.isNotBlank(reqDto.getUserId())) {
			dataPermissionService.cleanCompanyCacheByPartner(Long.parseLong(reqDto.getUserId()));
		}
		//推送微信消息
		sendWeixinMsgWithPremisesAudit(reqDto.getAgencyAccessToken(), reqDto.getCompanyUuid(), reqDto.getDomain(), reqDto.getId().toString(),premises.getPremisesStatus(),reqDto.getPremisesStatus(),premises.getSaleStatus());

		resDto.setResult(ResultEnum.SUCCESS.getNo());
		return resDto;
	}

	/**
	 * （14） 楼盘交易状态变更
	 *
	 * @param reqDto
	 * @return
	 */
	@Override
	public ChangePremisesSaleStatusResDto changePremisesSaleStatus(ChangePremisesSaleStatusReqDto reqDto) {
		ChangePremisesSaleStatusResDto resDto = new ChangePremisesSaleStatusResDto();

		//获取原来楼盘销售状态用于做对比
		Premises premises = premisesService.selectSimpleById(reqDto.getId());

		PremisesDto entity = new PremisesDto();
		entity.setId(reqDto.getId());
		entity.setSaleStatus(reqDto.getSaleStatus());
		entity.setCommissionWay("");
		entity.setReward("");
		entity.setCommission("");
		entity.setCommissionRate("");
		int updateRow = premisesService.audit(entity);

		// 查看是否有需要推送到V10 及推送微信消息
		if (updateRow > 0) {
			//推送微信消息
			sendWeixinMsgWithPremises(reqDto.getAgencyToken(), reqDto.getCompanyUuid(), reqDto.getDomain(), reqDto.getId().toString(),premises.getSaleStatus(),reqDto.getSaleStatus(),premises.getPremisesStatus());

			PremisesRelationExternalDto preDto = new PremisesRelationExternalDto();
			preDto.setIsDeleted(DelFlagEnum.UNDEL.getNo());
			preDto.setPremisesId(reqDto.getId());
			List<PremisesRelationExternal> premisesRelationExternalList = premisesRelationExternalService
					.selectListByDto(preDto);
			if (premisesRelationExternalList != null && premisesRelationExternalList.size() > 0) {
				//下架状态 调用下架就扣
				if(SaleStatusEnum.type_3.getNo().equals(reqDto.getSaleStatus())){
					v10BindService.issueFirsthandEstate(premises,premisesRelationExternalList, ShelvesStatusEnum.type0.getNo());
				}else{
					//非下架状态调用上架
					v10BindService.updateFirsthandEstateSaleStatus(premisesRelationExternalList, reqDto.getSaleStatus());
					v10BindService.issueFirsthandEstate(premises,premisesRelationExternalList, ShelvesStatusEnum.type1.getNo());
				}

			}
		}
		
		//清除楼盘权限缓存
		if(StringUtils.isNotBlank(reqDto.getUserId())) {
			dataPermissionService.cleanCompanyCacheByPartner(Long.parseLong(reqDto.getUserId()));
		}
		
		if (updateRow < 0) {
			resDto.setResult(ResultEnum.FAIL.getNo());
			resDto.setResultMsg("楼盘交易状态变更失败!");
			return resDto;
		}

		resDto.setResult(ResultEnum.SUCCESS.getNo());
		return resDto;
	}

	/**
	 * （15） 楼盘指定分销商
	 *
	 * @param reqDto
	 * @return
	 */
	@Override
	public AssignPremisesAgentResDto assignPremisesAgent(AssignPremisesAgentReqDto reqDto) {
		AssignPremisesAgentResDto resDto = new AssignPremisesAgentResDto();
		resDto.setResult(ResultEnum.SUCCESS.getNo());
		List<Long> premisesIds = reqDto.getPremisesIds();
		List<String> checkedAgentCompanyIds = reqDto.getAgentCompanyIds();
		if(CollectionUtils.isEmpty(premisesIds)){
			return resDto;
		}

		PartnerInfo pi = partnerInfoService.selectById(Long.valueOf(reqDto.getUserId()));
		CompanyRelationDto companyRelationDto = new CompanyRelationDto();
		companyRelationDto.setDevCompany(pi.getHigherid());
		List<CompanyRelationDto> crDtoList = companyRelationService.selectDtoListByDto(companyRelationDto);
		List<Long> allAgentCompanyIds = crDtoList.stream()
				.map(CompanyRelationDto::getAgentCompany)
				.collect(Collectors.toList());

		for(Long premisesId: premisesIds){
			//获取楼盘信息
			Premises premises = premisesMapper.selectById(premisesId);
			if(Objects.isNull(premises)){
				return resDto;
			}
			setPremisesRelation(premises, checkedAgentCompanyIds, allAgentCompanyIds);
		}
		return resDto;
	}

	void setPremisesRelation(Premises premises, List<String> checkedAgentCompanyIds, List<Long> allAgentCompanyIds){
		try{
			Long premisesId = premises.getId();
			List<Long> upCompanyIds = new ArrayList<>();
			List<Long> downCompanyIds = new ArrayList<>();
			// 先将原有楼盘的合作的经纪公司的Status都置为无效
			PremisesRelationDto entity = new PremisesRelationDto();
			entity.setPremisesId(premisesId);
			List<PremisesRelation> prList = premisesRelationService.selectListByDto(entity);
			List<Long> prAgentCompanyIds = prList.stream()
					.map(PremisesRelation::getAgentCompanyId)
					.collect(Collectors.toList());
			// 已建立绑定关系的分销公司
			List<Long> existCompanyIds = allAgentCompanyIds.stream()
					.filter(item -> prAgentCompanyIds.contains(item))
					.collect(Collectors.toList());
			// 已建立绑定关系的分销公司且本次本选中的公司,执行指定操作
			List<Long> existCheckedCompanyIds = existCompanyIds.stream()
					.filter(item -> checkedAgentCompanyIds.contains(String.valueOf(item)))
					.collect(Collectors.toList());
			// 筛选出已取消绑定,本次新绑定的记录
			List<PremisesRelation> newBindPrList = prList.stream()
					.filter(item -> RelationStatusEnum.INVALID.getNo().equals(item.getStatus())
							&& existCheckedCompanyIds.contains(item.getAgentCompanyId())
					).collect(Collectors.toList());
			// 添加绑定及发送上架消息
			if(CollectionUtils.isNotEmpty(newBindPrList)){
				// 取消选中
				List<String> bindIds = newBindPrList.stream().map(item -> String.valueOf(item.getId())).collect(Collectors.toList());
				PremisesRelationDto dto = new PremisesRelationDto();
				dto.setStatus(MechanismStatusEnum.enable.getNo());
				premisesRelationService.updates(dto, String.join(",", bindIds));
				// 发送上架消息涉及公司
				List<Long> companyIds = newBindPrList.stream().map(PremisesRelation::getAgentCompanyId).collect(Collectors.toList());
				upCompanyIds.addAll(companyIds);
			}

			// 已建立绑定关系的分销公司且未被选中的公司,执行取消指定操作
			List<Long> existUNCheckedCompanyIds = existCompanyIds.stream()
					.filter(item -> !checkedAgentCompanyIds.contains(String.valueOf(item)))
					.collect(Collectors.toList());
			// 筛选出已绑定,本次取消绑定的记录
			List<PremisesRelation> cancelPrList = prList.stream()
					.filter(item -> RelationStatusEnum.VALID.getNo().equals(item.getStatus())
							&& existUNCheckedCompanyIds.contains(item.getAgentCompanyId())
					).collect(Collectors.toList());
			// 取消绑定及发送下架消息
			if(CollectionUtils.isNotEmpty(cancelPrList)){
				// 取消选中
				List<String> cancelIds = cancelPrList.stream().map(item -> String.valueOf(item.getId())).collect(Collectors.toList());
				PremisesRelationDto dto = new PremisesRelationDto();
				dto.setStatus(MechanismStatusEnum.disable.getNo());
				premisesRelationService.updates(dto, String.join(",", cancelIds));
				// 发送下架通知
				List<Long> companyIds = cancelPrList.stream().map(PremisesRelation::getAgentCompanyId).collect(Collectors.toList());
				downCompanyIds.addAll(companyIds);
			}

			// 未建立绑定关系的分销公司
			List<Long> notExistCompanyIds = allAgentCompanyIds.stream()
					.filter(item -> !prAgentCompanyIds.contains(item))
					.collect(Collectors.toList());
			// 未建立绑定关系的分销公司且本次本选中的公司,新增绑定记录
			List<Long> notExistCheckedCompanyIds = notExistCompanyIds.stream()
					.filter(item -> checkedAgentCompanyIds.contains(String.valueOf(item)))
					.collect(Collectors.toList());
			if(CollectionUtils.isNotEmpty(notExistCheckedCompanyIds)){
				upCompanyIds.addAll(notExistCheckedCompanyIds);
				for(Long bindCompany: notExistCheckedCompanyIds){
					PremisesRelationDto addPrDto = new PremisesRelationDto();
					addPrDto.setDevCompanyId(premises.getCompanyId());
					addPrDto.setAgentCompanyId(bindCompany);
					addPrDto.setPremisesId(premisesId);
					addPrDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
					addPrDto.setStatus(RelationStatusEnum.VALID.getNo());
					premisesRelationService.create(addPrDto);
				}
			}
			// 未建立绑定关系的分销公司且未被选中的公司,新增取消绑定记录
			List<Long> notExistUNCheckedCompanyIds = notExistCompanyIds.stream()
					.filter(item -> !checkedAgentCompanyIds.contains(String.valueOf(item)))
					.collect(Collectors.toList());
			if(CollectionUtils.isNotEmpty(notExistUNCheckedCompanyIds)){
				downCompanyIds.addAll(notExistUNCheckedCompanyIds);
				for(Long unBindCompany: notExistUNCheckedCompanyIds){
					PremisesRelationDto addPrDto = new PremisesRelationDto();
					addPrDto.setDevCompanyId(premises.getCompanyId());
					addPrDto.setAgentCompanyId(unBindCompany);
					addPrDto.setPremisesId(premisesId);
					addPrDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
					addPrDto.setStatus(RelationStatusEnum.INVALID.getNo());
					premisesRelationService.create(addPrDto);
				}
			}

			PremisesRelationExternalDto preDto = new PremisesRelationExternalDto();
			/**
			 * 判断需要上架的分销商是否存在
			 */
			if (CollectionUtils.isNotEmpty(upCompanyIds)){
				preDto.setAgentCompanyIds(upCompanyIds);
				preDto.setPremisesId(premisesId);
				preDto.setIsDeleted(DelFlagEnum.UNDEL.getNo());
				List<PremisesRelationExternal> upPreList = premisesRelationExternalService.selectListByDto(preDto);
				v10BindService.issueFirsthandEstate(premises, upPreList, ShelvesStatusEnum.type1.getNo());
			}

			/**
			 * 判断需要下架的分销商是否存在
			 */
			if (CollectionUtils.isNotEmpty(downCompanyIds)){
				preDto = new PremisesRelationExternalDto();
				preDto.setAgentCompanyIds(downCompanyIds);
				preDto.setPremisesId(premisesId);
				preDto.setIsDeleted(DelFlagEnum.UNDEL.getNo());
				List<PremisesRelationExternal> downPreList = premisesRelationExternalService.selectListByDto(preDto);
				v10BindService.issueFirsthandEstate(premises, downPreList, ShelvesStatusEnum.type0.getNo());
			}
		}catch(Exception ex){
			logger.error("premisesApiServiceImpl --> setPremisesRelation error: {}", ex);
		}
	}

	/**
	 * 获取原关系表ID
	 * @param entity
	 * @return
	 */
	private String getOldIds(PremisesRelationDto entity) {
		String ids = "";
		List<PremisesRelation> lists = premisesRelationService.selectListByDto(entity);
		StringBuffer sb = new StringBuffer();
		for (PremisesRelation pre : lists) {
			sb.append(pre.getId() + ",");
		}
		ids = sb.toString();
		if (ids.length() > 1) {
			ids = ids.substring(0, ids.length() - 1);
		}
		return ids;
	}

	private List<String> getOldAgencyIds(PremisesRelationDto entity) {
		String ids = "";
        entity.setStatus("1");
        entity.setDelFlag(DelFlagEnum.UNDEL.getNo());
		List<PremisesRelation> lists = premisesRelationService.selectListByDto(entity);
		if(lists == null  || lists.size() == 0) {
		    return new ArrayList<>();
        }
		List<String> agencyIdList = lists.stream().map(premisesRelation -> premisesRelation.getAgentCompanyId()+"").collect(Collectors.toList());
		return agencyIdList;
	}

	/**
	 *
	 * @param premisesId
	 * @param ids 设为有效的用户
	 * @return
	 */
	private Map<String,List<String>> getChangeAgency(Long premisesId,String ids){
		Map<String,List<String>> map = new HashMap<>();
		List<String> cancelAgency = new ArrayList<>();
		List<String> confirmAgency = new ArrayList<>();
		String[] allSetIds = ids.split(",");


		//获取楼盘对应的分销商列表
		PremisesRelationDto premisesRelationDto = new PremisesRelationDto();
		premisesRelationDto.setPremisesId(premisesId);
		List<PremisesRelation> prList = premisesRelationService.selectListByDto(premisesRelationDto);
		for(PremisesRelation pr : prList){
			for (String s : allSetIds) {
				if(s.equals(pr.getId().toString()) && !RelationStatusEnum.VALID.getNo().equals(pr.getStatus())){
					//原来没有指定分销商，这次需要指定的
					confirmAgency.add(pr.getAgentCompanyId().toString());
					break;
				}
			}
			if(RelationStatusEnum.VALID.getNo().equals(pr.getStatus())){
				//原来指定分销商，这次取消指定的
				cancelAgency.add(pr.getAgentCompanyId().toString());
			}
		}
		map.put("cancelAgency",cancelAgency);
		map.put("confirmAgency",confirmAgency);
		return map;
	}
	/**
	 * （16） 楼盘明细
	 *
	 * @param reqDto
	 * @return
	 */
	@Override
	public GetPremisesDetailResDto getPremisesDetail(GetPremisesDetailReqDto reqDto) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		GetPremisesDetailResDto resDto = new GetPremisesDetailResDto();

		PremisesDto entity = new PremisesDto();
		entity.setId(reqDto.getId());
		List<Premises> premisesList = premisesService.getListModelByAcreage(entity);

		Map<String, String> map = new HashMap<>(16);
		if (null != premisesList && premisesList.size() > 0) {
			Premises premises = premisesList.get(0);
			PremisesDetailResDto detailResDto = new PremisesDetailResDto();
			BeanUtils.copyProperties(premises, detailResDto);
			String key = String.valueOf(detailResDto.getId());
			String value = "0";
			if (StringUtils.isNotBlank(map.get(key))) {
				value = map.get(key);
			}
			detailResDto.setReportCount(value);

			// 推荐人信息
			List<PremisesRecommenderDto> premisesRecommenderList = premisesRecommenderService.selectListForPremisesInfo(reqDto.getId());
			if(CollectionUtils.isNotEmpty(premisesRecommenderList)){
				detailResDto.setPremisesRecommenderList(premisesRecommenderList);
			}

			// 从楼盘中获取佣金、带看奖、结佣方式
			String commission = detailResDto.getCommission();
			String reward = detailResDto.getReward();
			String way = detailResDto.getCommissionWay();
			detailResDto.setCommission(commission);
			detailResDto.setReward(reward);
			if (StringUtils.isNotBlank(way) && !"0".equals(way)) {
				detailResDto.setCommissionWay(CommissionWayEnum.getDescByNo(way));
			} else {
				// 可能采用新增合作机构的结佣方式，但是之前的楼盘结佣方式有影响
				detailResDto.setCommissionWay("");
			}
			//报备方式
			if (StringUtils.isNotBlank(detailResDto.getReportWay())) {
				detailResDto.setReportWayCN(ReportWayEnum.getDescByNo(detailResDto.getReportWay()));
			}
			if (StringUtils.isNotBlank(reqDto.getUserId())) {
				// 楼盘有效报备数量
				CustomerPremisesDto cusPreDto = new CustomerPremisesDto();
				cusPreDto.setPremisesId(premises.getId());
				cusPreDto.setStaffId(Long.valueOf(reqDto.getUserId()));
				PartnerInfo pi = partnerInfoService.selectById(Long.valueOf(reqDto.getUserId()));
				if ("0".equals(pi.getAccountType())) {
					cusPreDto.setStaffId(null);
				}
				int count = customerPremisesService.count(cusPreDto);
				detailResDto.setRecommendCount(String.valueOf(count));
			}
			List<Integer> imgTypeList = Arrays.asList(60, 70, 80, 90);
			detailResDto.setLicenseList(premisesImageMapper.selectListbyImageType(reqDto.getId(), imgTypeList));
			// 物业类型
			if (StringUtils.isNotBlank(detailResDto.getEstateType())) {
				String ids = detailResDto.getEstateType();
				if (ids.indexOf(",") != -1) {
					String[] list = detailResDto.getEstateType().split(",");
					StringBuffer sb = new StringBuffer();
					for (String id : list) {
						String name = EstateTypeEnum.getByNo(id).getDes();
						sb.append(name + ",");
					}
					if (sb.length() > 0) {
						detailResDto.setEstateTypeCN(sb.toString().substring(0, sb.toString().length() - 1));
					}
				} else {
					detailResDto.setEstateTypeCN(EstateTypeEnum.getByNo(ids).getDes());
				}
			}

			// 建筑类别
			if (StringUtils.isNotBlank(detailResDto.getBuildingType())) {
				String ids = detailResDto.getBuildingType();
				if (ids.indexOf(",") != -1) {
					String[] list = detailResDto.getBuildingType().split(",");
					StringBuffer sb = new StringBuffer();
					for (String id : list) {
						String name = AbroadBuildingTypeEnum.getByNo(id).getDes();
						sb.append(name + ",");
					}
					if (sb.length() > 0) {
						detailResDto.setBuildingTypeCN(sb.toString().substring(0, sb.toString().length() - 1));
					}
				} else {
					detailResDto.setBuildingTypeCN(AbroadBuildingTypeEnum.getByNo(ids).getDes());
				}
			}
			// 楼盘标签
			if (StringUtils.isNotBlank(detailResDto.getCodeName())) {
				String codeValues = detailResDto.getCodeName();
				BaseCodeValueDto en = new BaseCodeValueDto();
				en.setIds(detailResDto.getCodeName());
				List<BaseCodeValue> list = baseCodeValueService.selectListByDto(en);
				StringBuffer sb = new StringBuffer();
				for (BaseCodeValue codeValue : list) {
					sb.append(codeValue.getCodeName() + ",");
				}
				if (sb.toString().length() > 0) {
					detailResDto.setCodeNameCN(sb.toString().substring(0, sb.toString().length() - 1));
				}
			}
			// 楼盘图片
			ApartmentLayoutDiagramDto aldDto = new ApartmentLayoutDiagramDto();
			aldDto.setPremisesId(premises.getId());
			List<ApartmentLayoutDiagram> aldList = apartmentLayoutDiagramService.selectListByDto(aldDto);
			for (ApartmentLayoutDiagram ad : aldList) {
				ad.setAprtmentInfo(getApartments(ad.getApartmentLayout()));
			}
			detailResDto.setImgList(aldList);
			// 楼盘封面
			detailResDto.setImgUrl(premises.getUrl());
			// 楼盘动态
			List<PremisesDynamic> premisesDynamicList;
			PremisesDynamicDto preDynDto = new PremisesDynamicDto();
			preDynDto.setPremisesId(premises.getId());
			preDynDto.setCanSee(true);
			if(SystemIdEnum.WEAPP_AGENCY.getCode().equals(reqDto.getLoginType())) {
				//优化。分销小程序详情只加载一条，后续动态详情分页加载
				preDynDto.setOrders(" t.update_time desc");
				premisesDynamicList = premisesDynamicService.getPageModel(preDynDto, 0, 1).getRows();
			}else {
				premisesDynamicList = premisesDynamicService.selectListByDto(preDynDto);
			}
			if (null != premisesDynamicList) {
				List<PreDynamic> preDynamicList = new ArrayList<PreDynamic>();
				for (PremisesDynamic premisesDynamic : premisesDynamicList) {
					PreDynamic preDynamic = new PreDynamic();
					String title = premisesDynamic.getTitle();
					Date createTime = premisesDynamic.getCreateTime();
					Date updateTime = premisesDynamic.getUpdateTime();
					String timeStr = "";
					if (null != createTime) {
						timeStr = sdf.format(createTime);
					}
					if (null != updateTime) {
						timeStr = sdf.format(updateTime);
					}
					preDynamic.setTitle(title);
					preDynamic.setCreateTime(timeStr);
					preDynamic.setId(String.valueOf(premisesDynamic.getId()));
					//分销小程序特有
					if(SystemIdEnum.WEAPP_AGENCY.getCode().equals(reqDto.getLoginType())) {
						preDynamic.setUpdateTime(timeStr.replaceAll("-", "."));
						preDynamic.setContent(premisesDynamic.getContent());
						preDynamic.setRemark(premisesDynamic.getRemark());
					}
					preDynamicList.add(preDynamic);
				}
				detailResDto.setPreDynamicList(preDynamicList);
			}

			// 获取楼盘相册

			List<PremisesImage> listImage = premisesImageMapper.selectListbyImageType(premises.getId(),
					Arrays.asList(3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13));
			Map<String, List<PremisesImageDto>> premisesImageMap = new HashMap<String, List<PremisesImageDto>>();
			for (PremisesImage pi : listImage) {
				PremisesImageDto dto = new PremisesImageDto();
				BeanUtils.copyProperties(pi, dto);
				if (premisesImageMap.containsKey(pi.getImageType())) {
					premisesImageMap.get(pi.getImageType()).add(dto);
				} else {
					premisesImageMap.put(pi.getImageType(), new ArrayList<PremisesImageDto>(Arrays.asList(dto)));
				}
			}
			resDto.setPremisesImages(premisesImageMap);

			// 楼盘驻守人员(取一人)
			CaseMemberDto cmDto = new CaseMemberDto();
			cmDto.setPremisesId(premises.getId());
			cmDto.setPiStatus(MechanismStatusEnum.enable.getNo());
			cmDto.setOrders("t.create_time desc");
			List<CaseMemberDto> cmDtoList = caseMemberService.selectParAndPreListByDto(cmDto);
			LinkedList<PartnerInfo> partnerInfos = new LinkedList<>();
			PartnerInfo pi = null;
			if (null != cmDtoList && cmDtoList.size() > 0) {
				for (CaseMemberDto dto : cmDtoList) {
					if("1".equals(dto.getPhoneStatus())){
						pi = partnerInfoService.selectById(dto.getPartnerId());
						if (null != pi) {
							break;
						}
					}else{
						// 优化。因为只取第一个，所以不用查很多次。
						if(partnerInfos.size() != 0) {
							continue;
						}
						PartnerInfo p = partnerInfoService.selectById(dto.getPartnerId());
						if (null != p) {
							partnerInfos.add(p);
						}
					}

				}
			}
			Long roleId = null;
			if (null != pi) {
				if (StringUtils.isNotBlank(pi.getAccountName()) && StringUtils.isNotBlank(pi.getPhone())) {
					detailResDto.setCaseMemberName(pi.getAccountName());
					detailResDto.setCaseMemberPhone(pi.getPhone());
					roleId = pi.getUserRoleId();
				}
			}else if(partnerInfos.size() > 0){
				if (StringUtils.isNotBlank(partnerInfos.get(0).getAccountName()) && StringUtils.isNotBlank(partnerInfos.get(0).getPhone())) {
					detailResDto.setCaseMemberName(partnerInfos.get(0).getAccountName());
					detailResDto.setCaseMemberPhone(partnerInfos.get(0).getPhone());
					roleId = partnerInfos.get(0).getUserRoleId();
				}
			}
			if(roleId != null) {
				ChannelRoleDto roleDto = new ChannelRoleDto();
				roleDto.setId(roleId);
				ChannelRole channelRole = channelRoleMapper.selectByDto(roleDto);
				String roleName = channelRole == null? null: channelRole.getRoleName();
				detailResDto.setCaseMemberRoleName(roleName);
			}
			//分销小程序的时候转换楼盘封面图链接
			if(SystemIdEnum.WEAPP_AGENCY.getCode().equals(reqDto.getLoginType())) {
				String url = detailResDto.getUrl();
				if(StringUtil.isNotNull(url)) {
					String newUrl = QiNiuUtil.convertFileToQiniu(url);
					if(!url.equals(newUrl)) {
						//设置返回链接，更新楼盘返回值
						detailResDto.setUrl(newUrl);
						PremisesDto entity1 = new PremisesDto();
						entity1.setId(reqDto.getId());
						entity1.setUrl(newUrl);
						premisesService.update(entity1);
					}
				}
			}
			
			// 将结果返回
			if (Objects.nonNull(premises) && !TimeUnitTypeEnum.NONE.getNo().equals(premises.getSpecialTimeType())
					&& StringUtils.isNotBlank(premises.getSpecialTime())) {
				detailResDto.setSpecialTime(premises.getSpecialTime());
			}

			resDto.setDetailResDto(detailResDto);
		}

		resDto.setResult(ResultEnum.SUCCESS.getNo());
		return resDto;
	}
	

	/**
	 * （18） 楼盘是否有效
	 *
	 * @param reqDto
	 * @return
	 */
	@Override
	public CheckPremisesValidResDto checkPremisesValid(CheckPremisesValidReqDto reqDto) {
		CheckPremisesValidResDto resDto = new CheckPremisesValidResDto();

		// 查询全部有效数据
		Premises premises = premisesService.selectSimpleById(reqDto.getId());
		if (premises == null) {
			// 无效
			resDto.setValid("0");
		} else {
			// 有效
			resDto.setValid("1");
		}

		return resDto;
	}

	/**
	 * （19） 楼盘动态Page
	 *
	 * @param reqDto
	 * @return
	 */
	@Override
	public GetPremisesDynamicPageResDto getPremisesDynamicPage(GetPremisesDynamicPageReqDto reqDto) {
		GetPremisesDynamicPageResDto resDto = new GetPremisesDynamicPageResDto();

		int pageNo = reqDto.getPageNo();
		int pageSize = reqDto.getPageSize();

		// 查询合作机构
		PartnerInfo partnerInfo = partnerInfoService.selectById(stringToLong(reqDto.getUserId()));
		if (partnerInfo == null) {
			resDto.setResult(ResultEnum.FAIL.getNo());
			resDto.setResultMsg("未获取到合作机构!");
			return resDto;
		}

		// 设置条件
		PremisesDynamicDto entity = new PremisesDynamicDto();
		// 判断是否管理员(0是 1否)
		List<Long> premisesIds = new ArrayList<>();
		if (!PartnerInfoEnum.ACCOUNT_MECHANISM.getCode().equals(partnerInfo.getAccountType())) {
			CaseMemberDto dto = new CaseMemberDto();
			dto.setPartnerId(partnerInfo.getId());
			dto.setPreStatus(SaleStatusEnum.type_1.getNo());
			List<CaseMember> list = caseMemberService.selectListByDto(dto);
			if (list.size() == 0) {
				// 查不到楼盘数据，则匹配-1
				entity.setPremisesId(Long.valueOf("-1"));
			} else {
				for (CaseMember cm : list) {
					premisesIds.add(cm.getPremisesId());
				}
                //当前登录人是否为楼盘项目总监或项目经理
                PremisesDto premisesDto = new PremisesDto();
                premisesDto.setMobileTemp(partnerInfo.getPhone());
                premisesDto.setCompanyId(partnerInfo.getHigherid());
                List<Premises> premisesList = premisesService.selectIdListByMobileTemp(premisesDto);
                if(premisesList != null && premisesList.size() > 0) {
                    for (Premises premises : premisesList) {
                        premisesIds.add(premises.getId());
                    }
                }
				entity.setPremisesIds(premisesIds);
			}
		} else {
			entity.setCompanyId(partnerInfo.getHigherid());
		}

		if (partnerInfo.getObjectType() != null) {
			// 公司类型
			long objectType = partnerInfo.getObjectType();
			// 查询对应字典值
			Dictionary dictionary = dictionaryService.selectById(objectType);
			if (dictionary != null) {
				// 获取value
				String value = dictionary.getDicValue();
				if (value.equals(CompanyTypeEnum.COMPANY_TYPE_VALUE_0.getCode())) {
					// 中介账号通过地域属性过滤
					if (partnerInfo.getCity() != null) {
						entity.setAreaId(partnerInfo.getCity());
					} else {
						List<Area> areaInfo = areaService.selectChildren(partnerInfo.getProvince());
						List<Long> array = new ArrayList<>();
						for (int i = 0; i < areaInfo.size(); i++) {
							array.add(areaInfo.get(i).getId());
						}
						entity.setCityIn(array);
					}
				} else if (value.equals(CompanyTypeEnum.COMPANY_TYPE_VALUE_2.getCode())) {
					// 开发商账户
					entity.setCompanyId(partnerInfo.getHigherid());
					// 省份
					if (reqDto.getProvince() != null) {
						entity.setProvinceId(reqDto.getProvince());
					}
					// 城市
					if (reqDto.getCity() != null) {
						entity.setCityId(reqDto.getCity());
					}
					// 区域
					if (reqDto.getArea() != null) {
						entity.setAreaId(reqDto.getArea());
					}
				}
			}
		}
		// 楼盘名称
		if (StringUtils.isNotBlank(reqDto.getName())) {
			entity.setName(reqDto.getName());
		}
		entity.setOrders("t.create_time desc");
		Page<PremisesDynamic> page = premisesDynamicService.getPageModelNew(entity, PageUtil.begin(pageNo, pageSize),
				pageSize);
		//获取动态id,查询V10推送记录
		List<Long> dynamicIds = page.getRows().stream().map(PremisesDynamic::getId).collect(Collectors.toList());
		List<PremisesDynamicExternal> premisesDynamicExternals = premisesDynamicExternalService.selectPremisesDynamicExternalByDynamicIds(dynamicIds);
		if (CollectionUtils.isNotEmpty(premisesDynamicExternals)){
			//如果有查询到推送记录，则设置已推送否则为未推送
			for (PremisesDynamic premisesDynamic : page.getRows()) {
				for (PremisesDynamicExternal externals : premisesDynamicExternals) {
					if (premisesDynamic.getId().equals(externals.getDynamicId())){
						premisesDynamic.setIsBindingV10("已推送");
						break;
					}
					premisesDynamic.setIsBindingV10("未推送");
				}
			}
		}else{
			page.getRows().forEach(premisesDynamic -> premisesDynamic.setIsBindingV10("未推送"));
		}
		resDto.setPremisesDynamicList(page);
		resDto.setResult(ResultEnum.SUCCESS.getNo());
		return resDto;
	}

	/**
	 * （21） 楼盘动态新增
	 *
	 * @param reqDto
	 * @return
	 */
	@Override
	@Transactional
	public AddOrEditPremisesDynamicResDto addPremisesDynamic(AddOrEditPremisesDynamicReqDto reqDto) {
		AddOrEditPremisesDynamicResDto resDto = new AddOrEditPremisesDynamicResDto();

		// 获取楼盘信息
		Premises premises = premisesService.selectSimpleById(reqDto.getPremisesId());
		if (premises == null) {
			resDto.setResult(ResultEnum.FAIL.getNo());
			resDto.setResultMsg("未获取到楼盘信息!");
			return resDto;
		}

		PremisesDynamicDto entity = new PremisesDynamicDto();
		entity.setPremisesId(premises.getId());
		entity.setPremisesName(premises.getName());
		// 标题
		entity.setTitle(reqDto.getTitle());
		// 内容
        entity.setContent(reqDto.getContent());
        // 简介
        entity.setRemark(reqDto.getRemark());
        // 是否可见，0否，1是
		if ("false".equals(reqDto.getCanSee())) {
			entity.setCanSee(false);
		} else if ("true".equals(reqDto.getCanSee())) {
			entity.setCanSee(true);
		}
		PremisesDynamicDto dto = premisesDynamicService.create(entity);
		if (dto == null) {
			resDto.setResult(ResultEnum.FAIL.getNo());
			resDto.setResultMsg("楼盘动态新增失败!");
			return resDto;
		}

		// 判断是否需要推到V10 获取 推送的楼盘关系
		PremisesRelationExternalDto preDto = new PremisesRelationExternalDto();
		preDto.setPremisesId(premises.getId());
		preDto.setIsDeleted(DelFlagEnum.UNDEL.getNo());
		preDto.setSysId(ExternalSysEnum.V10.getCode());
		List<PremisesRelationExternal> preList = premisesRelationExternalService.selectListByDto(preDto);
		if (preList != null && preList.size() > 0) {
			List<PremisesDynamicExternal> pdDtoList = new ArrayList<PremisesDynamicExternal>();
			for (PremisesRelationExternal pre : preList) {
				PremisesDynamicExternalDto pdeDto = new PremisesDynamicExternalDto();
				pdeDto.setPremisesId(premises.getId());
				pdeDto.setPremisesUuid(pre.getExternalId());
				pdeDto.setExternalCompanyId(pre.getExternalCompanyId());
				pdeDto.setDynamicId(dto.getId());
				pdDtoList.add(pdeDto);
			}
			try {
				entity.setContent(URLDecoder.decode(reqDto.getContent(), "utf-8"));
			} catch (UnsupportedEncodingException e) {
				logger.error("楼盘动态解码失败: {}", e);
			}
			// 简介
			try {
				entity.setRemark(URLDecoder.decode(reqDto.getRemark(), "utf-8"));
			} catch (UnsupportedEncodingException e) {
				logger.error("楼盘动态解码失败: {}", e);
			}

			List<BaseResponseDto> baseResponseDto = v10BindService.saveFirsthandEstateDynamic(pdDtoList, entity);
		}

		resDto.setResult(ResultEnum.SUCCESS.getNo());
		return resDto;
	}

	/**
	 * （22） 楼盘动态修改
	 *
	 * @param reqDto
	 * @return
	 */
	@Override
	public AddOrEditPremisesDynamicResDto editPremisesDynamic(AddOrEditPremisesDynamicReqDto reqDto) {
		AddOrEditPremisesDynamicResDto resDto = new AddOrEditPremisesDynamicResDto();

		// 获取楼盘信息
		Premises premises = premisesService.selectSimpleById(reqDto.getPremisesId());
		if (premises == null) {
			resDto.setResult(ResultEnum.FAIL.getNo());
			resDto.setResultMsg("未获取到楼盘信息!");
			return resDto;
		}

		PremisesDynamicDto entity = new PremisesDynamicDto();
		// 楼盘ID
		entity.setPremisesId(premises.getId());
		// 楼盘名字
		entity.setPremisesName(premises.getName());
		// 楼盘动态ID
		entity.setId(reqDto.getId());
		// 标题
		entity.setTitle(reqDto.getTitle());
		// 内容
		entity.setContent(reqDto.getContent());
		// 简介
		entity.setRemark(reqDto.getRemark());
		// 是否可见，0否，1是
		if ("false".equals(reqDto.getCanSee())) {
			entity.setCanSee(false);
		} else if ("true".equals(reqDto.getCanSee())) {
			entity.setCanSee(true);
		}
		int update = premisesDynamicService.update(entity);
		if (update == 0) {
			resDto.setResult(ResultEnum.FAIL.getNo());
			resDto.setResultMsg("楼盘动态修改失败!");
			return resDto;
		}
		// 判断是否需要推到V10

		PremisesDynamicExternalDto pdeDto = new PremisesDynamicExternalDto();
		pdeDto.setPremisesId(premises.getId());
		pdeDto.setIsDeleted(DelFlagEnum.UNDEL.getNo());
		pdeDto.setSysId(ExternalSysEnum.V10.getCode());
		List<PremisesDynamicExternal> pdeList = premisesDynamicExternalService.selectListByDto(pdeDto);
		if (pdeList != null && pdeList.size() > 0) {
			try {
				entity.setContent(URLDecoder.decode(reqDto.getContent(), "utf-8"));
			} catch (UnsupportedEncodingException e) {
				logger.error("楼盘动态解码失败: {}", e);
			}
			// 简介
			try {
				entity.setRemark(URLDecoder.decode(reqDto.getRemark(), "utf-8"));
			} catch (UnsupportedEncodingException e) {
				logger.error("楼盘动态解码失败: {}", e);
			}
			List<BaseResponseDto> baseResponseDto = v10BindService.saveFirsthandEstateDynamic(pdeList, entity);
		}
		resDto.setResult(ResultEnum.SUCCESS.getNo());
		return resDto;
	}

	/**
	 * （23） 楼盘动态详情
	 *
	 * @param reqDto
	 * @return
	 */
	@Override
	public GetPremisesDynamicDetailResDto getPremisesDynamicDetail(GetPremisesDynamicDetailReqDto reqDto) {
		GetPremisesDynamicDetailResDto resDto = new GetPremisesDynamicDetailResDto();

		PremisesDynamic premisesDynamic = premisesDynamicService.selectById(reqDto.getId());
		if (premisesDynamic != null) {
			try {
                premisesDynamic.setContent(URLDecoder.decode(premisesDynamic.getContent(), "utf-8"));
                premisesDynamic.setRemark(URLDecoder.decode(premisesDynamic.getRemark(), "utf-8"));
                //查看是否推送
				List<PremisesDynamicExternal> externalList = premisesDynamicExternalService.selectPremisesDynamicExternalByDynamicIds(Lists.newArrayList(premisesDynamic.getId()));
				premisesDynamic.setIsBindingV10(CollectionUtils.isEmpty(externalList) ? "未推送" : "已推送");
			} catch (Exception e) {
                logger.error("URLDecoder decode error: {}", e);
            }
        }
		resDto.setPremisesDynamic(premisesDynamic);
		resDto.setResult(ResultEnum.SUCCESS.getNo());
		return resDto;
	}

	/**
	 * （25） 楼盘户型图
	 *
	 * @param reqDto
	 * @return
	 */
	@Override
	public GetPremisesHxtResDto getPremisesHxt(GetPremisesHxtReqDto reqDto) {
		GetPremisesHxtResDto resDto = new GetPremisesHxtResDto();

		List<Map<String, String>> list = new ArrayList<Map<String, String>>();

		ApartmentLayoutDiagramDto entity = new ApartmentLayoutDiagramDto();
		entity.setPremisesId(reqDto.getId());
		List<ApartmentLayoutDiagram> adList = apartmentLayoutDiagramService.selectListByDto(entity);
		if (adList == null) {
			resDto.setGetPremisesHxt(list);
			resDto.setResult(ResultEnum.SUCCESS.getNo());
			return resDto;
		}
		for (ApartmentLayoutDiagram ad : adList) {
			Map<String, String> map = new HashMap<String, String>();
			String area = ad.getArea();
			if(area.indexOf(",") > 0){
				String[] areaArray = area.split(",");
				if(areaArray.length > 1){
					String one = areaArray[0];
					String two = areaArray[1];
					if(one.equals(two)){
						ad.setArea(one);
					}else{
						ad.setArea(one + " ~ " + two);
					}
				}
			}
			map.put("area", ad.getArea());
			map.put("apartmentLayout", ad.getApartmentLayout());
			map.put("imgUrl", ad.getUrl());
			map.put("huxingName", ad.getHuxingName());
			map.put("averagePrice", ad.getAveragePrice() == null ? null : ad.getAveragePrice().toString());
			list.add(map);
		}

		resDto.setGetPremisesHxt(list);
		resDto.setResult(ResultEnum.SUCCESS.getNo());
		return resDto;
	}

	/**
	 * 此代码未作总代楼盘和分销商的关联。方法可用性需谨慎
	 */
	@Override
	public GetPremisesCityListResDto getPremisesCityListService(GetPremisesCityListReqDto getPremisesCityListReqDto)
			throws Exception {
		GetPremisesCityListResDto resDto = new GetPremisesCityListResDto();
		Long agentCompany = getPremisesCityListReqDto.getMerchantId();
		String domain = getPremisesCityListReqDto.getDomain();
		String companyUuid = getPremisesCityListReqDto.getCompanyUuid();
		Long devCompanyId = getPremisesCityListReqDto.getDevCompanyId();
		if (StringUtils.isNotBlank(domain) && StringUtils.isNotEmpty(companyUuid)) {
			CompanyDto entity = new CompanyDto();
			entity.setDomain(domain);
			entity.setCompanyUuid(companyUuid);
			entity.setDelFlag(DelFlagEnum.UNDEL.getNo());
			entity.setStatus("2");
			Company company = companyService.selectByDto(entity);
			if (company != null) {
				devCompanyId = company.getId();
			}
		}
		PremisesRelationDto prDto = new PremisesRelationDto();
		prDto.setAgentCompanyId(agentCompany);
		if (devCompanyId != null) {
			prDto.setDevCompanyId(devCompanyId);
		}
		prDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
		prDto.setStatus("1");
		List<PremisesRelation> crList = premisesRelationService.selectListByDto(prDto);
		List<Long> premisesIds = new ArrayList<>();
		if (null != crList && crList.size() > 0) {
			for (PremisesRelation cr : crList) {
				premisesIds.add(cr.getPremisesId());
			}
		}

		PremisesDto preDto = new PremisesDto();
		// preDto.setDevCompanyIds(devCompanyIds);
		preDto.setCompanyId(devCompanyId);// 这里是分销助手根据开发商指定的楼盘查询，所以只有一个开发商id
		preDto.setOrders("a.full_name");
		preDto.setPremisesIds(premisesIds);
		// 楼盘所在城市集合
		List<ZPremisesDto> zpreDtoList = premisesService.selectPremisesCityListByDto(preDto);
		String[] letter = { "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R",
				"S", "T", "U", "V", "W", "X", "Y", "Z" };
		List<PremisesCityResDto> preCityResDtoList = new ArrayList<>();
		if (null != zpreDtoList) {
			for (int ii = 0; ii < letter.length; ii++) {
				PremisesCityResDto preCityResDto = new PremisesCityResDto();
				String en = letter[ii];
				List<PremisesCity> preCityList = new ArrayList<>();
				for (ZPremisesDto zpre : zpreDtoList) {
					if (null == zpre) {
						continue;
					}
					String cityName = zpre.getAreaName();
					String cityFirZh = cityName.substring(0, 1);
					String cityFirEn = ChineseCharToEn.getAllFirstLetter(cityFirZh);
					if (cityFirEn.equalsIgnoreCase(en)) {
						PremisesCity preCity = new PremisesCity();
						preCity.setCityId(String.valueOf(zpre.getCityId()));
						preCity.setCityName(cityName);
						preCityList.add(preCity);
					}
				}
				if (preCityList.size() > 0) {
					preCityResDto.setCityFirEn(en);
					preCityResDto.setPreCityList(preCityList);
					preCityResDtoList.add(preCityResDto);
				}
			}
		}
		resDto.setPremisesCityResDtoList(preCityResDtoList);
		resDto.setResult(ResultEnum.SUCCESS.getNo());
		return resDto;
	}

	@Override
	public GetPremisesCityGroupListResDto getPremisesCityGroupListService(
			GetPremisesCityGroupListReqDto reqDto) throws Exception {
		GetPremisesCityGroupListResDto resDto = new GetPremisesCityGroupListResDto();
		Long agentCompany = reqDto.getMerchantId();
		String domain = reqDto.getDomain();
		String companyUuid = reqDto.getCompanyUuid();
		Long devCompanyId = reqDto.getDevCompanyId();
        PartnerInfo partnerInfo = null;
		if(StringUtils.isNotBlank(reqDto.getUserId())){
            partnerInfo = partnerInfoService.selectById(Long.parseLong(reqDto.getUserId()));
        }

		if (StringUtils.isNotBlank(domain) || StringUtils.isNotEmpty(companyUuid)) {
			CompanyDto entity = new CompanyDto();
			entity.setDomain(domain);
			entity.setDelFlag(DelFlagEnum.UNDEL.getNo());
			entity.setCompanyUuid(companyUuid);
			entity.setStatus("2");
			Company company = companyService.selectByDto(entity);
			if (company != null && StringUtils.isNotBlank(company.getDomain())) {
				devCompanyId = company.getId();
			}
		}

		List<Long> premisesIds = new ArrayList<>();
		PremisesDto preDto = new PremisesDto();
		preDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
		preDto.setCompanyId(devCompanyId);// 这里是分销助手根据开发商指定的楼盘查询，所以只有一个开发商id
		if(partnerInfo != null && reqDto.getLoginType().equals(SystemIdEnum.ASSISTANT.getCode())) {
		    preDto.setListSaleStatus(Arrays.asList(new String[]{SaleStatusEnum.type_0.getNo(), SaleStatusEnum.type_1.getNo()}));
		    //获取最新楼盘的城市 市区 清空分销商信息
			agentCompany = null;
		    //如果登录人员为管理员
			if(!MechanismAccountTypeEnum.mechanism.getNo().equals(partnerInfo.getAccountType())){
                //非管理员 则查询助手信息
                CaseMemberDto caseMemberDto = new CaseMemberDto();
                caseMemberDto.setPartnerId(partnerInfo.getId());
                List<CaseMember> list = caseMemberService.selectListByDto(caseMemberDto);
                if(CollectionUtils.isEmpty(list)){
                    resDto.setPremisesCityList(new ArrayList<>());
                    resDto.setResult(ResultEnum.SUCCESS.getNo());
                    return resDto;
                }
                for(CaseMember m : list){
                    premisesIds.add(m.getPremisesId());
                }
			}
        } else if(reqDto.getLoginType().equals(SystemIdEnum.AGENCY_h5.getCode())
			|| reqDto.getLoginType().equals(SystemIdEnum.WEAPP_AGENCY.getCode())) {
		    preDto.setPremisesStatus(PremisesStatusEnum.type1.getNo());
            List<String> listSaleStatus = new ArrayList<>();
            listSaleStatus.add(SaleStatusEnum.type_1.getNo());
		    if(SystemIdEnum.WEAPP_AGENCY.getCode().equals(reqDto.getLoginType())) {
				listSaleStatus.add(SaleStatusEnum.type_0.getNo());
			}
            preDto.setListSaleStatus(listSaleStatus);
				
    		//查询指定分销商的楼盘
            if(Objects.nonNull(agentCompany)) {
                PremisesRelationDto prDto = new PremisesRelationDto();
                prDto.setAgentCompanyId(agentCompany);
                if (Objects.nonNull(devCompanyId)) {
                    prDto.setDevCompanyId(devCompanyId);
                }
                prDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
                prDto.setStatus("1");
                List<PremisesRelation> crList = premisesRelationService.selectListByDto(prDto);
                if(CollectionUtils.isEmpty(crList)){
                    //没有指定任何楼盘
                    resDto.setResult(ResultEnum.SUCCESS.getNo());
                    return resDto;
                }
                for (PremisesRelation cr : crList) {
                    premisesIds.add(cr.getPremisesId());
                }
            }else{
                //查询所有楼盘
                PremisesDto premisesDto = new PremisesDto();
                premisesDto.setCompanyId(devCompanyId);
                premisesDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
                List<Premises> premisesList = premisesService.selectSimpleListByDto(premisesDto);
                if (null != premisesList && premisesList.size() > 0) {
                    for (Premises p : premisesList) {
                        premisesIds.add(p.getId());
                    }
                }
            }
        }
        preDto.setOrders("a.pin_yin");
		if(!SystemIdEnum.WEAPP_AGENCY.getCode().equals(reqDto.getLoginType())) {
			preDto.setOrders("a.full_name");
		}
		//添加根据名称模糊搜索字段
		preDto.setCityName(reqDto.getCityName());
        List<String> listSaleStatus = new ArrayList<>();
        listSaleStatus.add(SaleStatusEnum.type_1.getNo());
		if(SystemIdEnum.WEAPP_AGENCY.getCode().equals(reqDto.getLoginType())) {
			listSaleStatus.add(SaleStatusEnum.type_0.getNo());
		}
        preDto.setListSaleStatus(listSaleStatus);
		preDto.setPremisesStatus(PremisesStatusEnum.type1.getNo());
		preDto.setPremisesIds(premisesIds);
		// 楼盘所在城市集合
		List<ZPremisesDto> zpreDtoList = premisesService.selectPremisesCityListByDto(preDto);
		List<PremisesCity> preCityList = new ArrayList<>();
		if (CollectionUtils.isNotEmpty(zpreDtoList)) {
			for (ZPremisesDto zpre : zpreDtoList) {
				if (Objects.isNull(zpre)) {
					continue;
				}
				String cityName = zpre.getAreaName();
				PremisesCity preCity = new PremisesCity();
				preCity.setCityId(String.valueOf(zpre.getCityId()));
				preCity.setCityName(cityName);
				preCity.setJustCityName(zpre.getJustAreaName());
				preCity.setPinYin(zpre.getPinYin());
                preCity.setPremisesCount(zpre.getPremisesCount()==null?0:zpre.getPremisesCount());
				preCityList.add(preCity);
			}
		}
		//获取最新的楼盘, 分销小程序用不到当前字段，减少查询
		if(!SystemIdEnum.WEAPP_AGENCY.getCode().equals(reqDto.getLoginType())) {
			Premises lastPremises = premisesService.getLastPremises(devCompanyId,agentCompany);
			if(lastPremises != null){
				resDto.setCityId(lastPremises.getCityId());
				resDto.setAreaId(lastPremises.getAreaId());
			}
		}
		
		resDto.setPremisesCityList(preCityList);
		resDto.setResult(ResultEnum.SUCCESS.getNo());
		return resDto;
	}

	@Override
	public GetPremisesGroupByCityResDto getPremisesGroupByCity(
			GetPremisesGroupByCityReqDto getPremisesGroupByCityReqDto) throws Exception {
		GetPremisesGroupByCityResDto resDto = new GetPremisesGroupByCityResDto();
		List<Long> devCompanyIds = new ArrayList<>();
		// 经纪人所属公司的合作开发商
		CompanyRelationDto crDto = new CompanyRelationDto();
		crDto.setAgentCompany(getPremisesGroupByCityReqDto.getMerchantId());
		crDto.setRelationStatus(RelationStatusEnum.VALID.getNo());
		crDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
		List<CompanyRelation> crList = companyRelationService.selectListByDto(crDto);
		if (null != crList && crList.size() > 0) {
			for (CompanyRelation cr : crList) {
				devCompanyIds.add(cr.getDevCompany());
			}
		}

		// 合作开发商所有楼盘所在城市
		PremisesDto preDto = new PremisesDto();
		preDto.setDevCompanyIds(devCompanyIds);
		List<ZPremisesDto> zpreDtoList = premisesService.selectPremisesCityListByDto(preDto);
		zpreDtoList = zpreDtoList.stream().filter(item -> (Objects.nonNull(item) && Objects.nonNull(item.getCityId())))
				.collect(Collectors.toList());
		List<PremisesGroupByCityResDto> pgbcResDtoList = new ArrayList<>();
		if (null != zpreDtoList) {
			// 拼装查询字典信息
			String[][] cityArr = new String[zpreDtoList.size()][];
			for (int ii = 0; ii < zpreDtoList.size(); ii++) {
				String[] cityInfo = new String[2];
				ZPremisesDto zpreDto = zpreDtoList.get(ii);
				String areaId = String.valueOf(zpreDto.getCityId());
				String cityName = zpreDto.getAreaName();
				cityInfo[0] = areaId;
				cityInfo[1] = cityName;
				cityArr[ii] = cityInfo;
			}

			preDto = new PremisesDto();
			preDto.setDevCompanyIds(devCompanyIds);
			preDto.setPremisesStatus(PremisesStatusEnum.type1.getNo());
			preDto.setSaleStatus(SaleStatusEnum.type_1.getNo());
			preDto.setOrders(
					" main_push desc,main_push_settime desc, CASE WHEN sequence IS NULL THEN 1 ELSE 0 END ASC,sequence ASC, t.premises_status asc, t.create_time desc");
			// 从楼盘关系表查对应楼盘id
			List<Long> premisesIds = new ArrayList<>();
			PremisesRelationDto relationDto = new PremisesRelationDto();
			relationDto.setAgentCompanyId(getPremisesGroupByCityReqDto.getMerchantId());
			relationDto.setDevCompanyId(devCompanyIds.get(0));
			relationDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
			relationDto.setStatus(MechanismStatusEnum.enable.getNo());
			List<PremisesRelationDto> list = premisesRelationService.selectMyListByDto(relationDto);
			for (PremisesRelationDto pre : list) {
				premisesIds.add(pre.getPremisesId());
			}
			preDto.setPremisesIds(premisesIds);
			List<Premises> premisesList = premisesService.selectIdListByDto(preDto);
			if (CollectionUtils.isNotEmpty(premisesList)) {
				for (int jj = 0; jj < cityArr.length; jj++) {
					PremisesGroupByCityResDto pgbcResDto = new PremisesGroupByCityResDto();
					List<PremisesGroupByCity> pgbcList = new ArrayList<>();
					String[] jjArr = cityArr[jj];
					if (null != jjArr) {
						String jjCityId = jjArr[0];
						String jjCityName = jjArr[1];
						for (Premises premises : premisesList) {
							String areaId = String.valueOf(premises.getCityId());
							if (jjCityId.equals(areaId)) {
								PremisesGroupByCity pgbc = new PremisesGroupByCity();
								pgbc.setPremisesId(String.valueOf(premises.getId()));
								pgbc.setPremisesName(premises.getName());
								pgbc.setProtectTime(premises.getVisitProtect());
								pgbc.setSpecialTime(premises.getSpecialTime());
								pgbc.setSpecialTimeType(premises.getSpecialTimeType());
								String cityAndPremisesName = "[" + jjCityName + "]" + premises.getName();
								pgbc.setCityAndPremisesName(cityAndPremisesName);
								pgbc.setProtectTimeType(premises.getVisitProtectType());
								pgbc.setReportProtect(premises.getReportProtect());
								pgbc.setReportProtectType(premises.getReportProtectType());
								pgbc.setReportWay(premises.getReportWay());
								pgbcList.add(pgbc);
							}
						}
						if (CollectionUtils.isNotEmpty(pgbcList)) {
							pgbcResDto.setCityName(jjCityName);
							pgbcResDto.setPreGroupByCityList(pgbcList);
							pgbcResDtoList.add(pgbcResDto);
						}
					}
				}
			}
		}
		resDto.setList(pgbcResDtoList);
		resDto.setResult(ResultEnum.SUCCESS.getNo());
		return resDto;
	}

	/**
	 * String转Long
	 *
	 * @param field
	 * @return Long
	 */
	private Long stringToLong(String field) {
		return StringUtils.isBlank(field) ? null : Long.parseLong(field);
	}

	/**
	 * 获取楼盘id集合
	 */
	@Override
	public List<Long> getPremisesIdsList(PartnerInfo partnerInfo) {
		List<Long> premisesIds = new ArrayList<>();
		// 是否是管理员(0是 1否)
		if (!PartnerInfoEnum.ACCOUNT_MECHANISM.getCode().equals(partnerInfo.getAccountType())) {
			CaseMemberDto entity = new CaseMemberDto();
			entity.setPremisesStatus(PremisesStatusEnum.type1.getNo());
			entity.setCompanyId(partnerInfo.getHigherid());
			entity.setPartnerId(partnerInfo.getId());
			List<CaseMember> list = caseMemberService.selectListByDto(entity);
			for (CaseMember cm : list) {
				premisesIds.add(cm.getPremisesId());
			}
		} else {
			PremisesDto entity = new PremisesDto();
			entity.setCompanyId(partnerInfo.getHigherid());
			entity.setPremisesStatus(PremisesStatusEnum.type1.getNo());
			//优化查询 查询字段太多数据库查询太慢
			//List<Premises> pl = premisesService.selectListByDto(entity);
			List<Premises> pl = premisesService.selectIdListByDto(entity);
			for (Premises pr : pl) {
				premisesIds.add(pr.getId());
			}
		}
		return premisesIds;
	}

	/**
	 * 楼盘刪除
	 *
	 * @param reqDto
	 * @return
	 */
	@Override
	public DeletePremisesResDto deletePremises(DeletePremisesReqDto reqDto) {
		DeletePremisesResDto resDto = new DeletePremisesResDto();

		PremisesDto dto = new PremisesDto();
		dto.setId(reqDto.getId());
		int deleteRow = premisesService.delete(dto);
		if (deleteRow > 0) {
			// 推送V10删除楼盘
			PremisesRelationExternalDto preDto = new PremisesRelationExternalDto();
			preDto.setIsDeleted(DelFlagEnum.UNDEL.getNo());
			preDto.setPremisesId(reqDto.getId());
			List<PremisesRelationExternal> premisesRelationExternalList = premisesRelationExternalService
					.selectListByDto(preDto);
			if (premisesRelationExternalList != null && premisesRelationExternalList.size() > 0) {
				v10BindService.deleteFirsthandEstate(premisesRelationExternalList);
			}
		}
		if (deleteRow <= 0) {
			resDto.setResult(ResultEnum.FAIL.getNo());
			resDto.setResultMsg("楼盘删除失败");
			return resDto;
		}
		resDto.setResult(ResultEnum.SUCCESS.getNo());
		return resDto;
	}

	/**
	 * 楼盘列表
	 *
	 * @param reqDto
	 * @return
	 */
	@Override
	public GetPremisesPageResDto getPremisesPage(GetPremisesPageReqDto reqDto) {
		GetPremisesPageResDto resDto = new GetPremisesPageResDto();

		// 查询合作机构
		PartnerInfo pi = partnerInfoService.selectById(stringToLong(reqDto.getUserId()));
		if (pi == null) {
			resDto.setResult(ResultEnum.FAIL.getNo());
			resDto.setResultMsg("未获取到合作机构!");
			return resDto;
		}
		int pageNo = reqDto.getPageNo();
		int pageSize = reqDto.getPageSize();
		String name = reqDto.getName();
		Long provinceId = reqDto.getProvinceId();
		Long cityId = reqDto.getCityId();
		Long areaId = reqDto.getAreaId();
		String estateType = reqDto.getEstateType();
		String averagePrice = reqDto.getAveragePrice();
		String acreage = reqDto.getAcreage();
		String premisesStatus = reqDto.getPremisesStatus();

		PremisesDto dto = new PremisesDto();
		dto.setCompanyId(pi.getHigherid());
		if (null != provinceId) {
			dto.setProvinceId(provinceId);
		}
		if (null != cityId) {
			dto.setCityId(cityId);
		}
		if (null != areaId) {
			dto.setAreaId(areaId);
		}
		if (StringUtils.isNotBlank(premisesStatus)) {
			dto.setPremisesStatus(premisesStatus);
		}
		if (StringUtils.isNotBlank(estateType)) {
			dto.setEstateType(estateType);
		}
		if (StringUtils.isNotBlank(acreage)) {
			dto.setAcreage(acreage);
		}
		if (StringUtils.isNotBlank(averagePrice)) {
			dto.setAveragePrice(null);
			if (averagePrice.contains("<=")) {
				dto.setSufAveragePrice(Long.valueOf(averagePrice.substring(2)));
			}
			if (averagePrice.contains(">")) {
				dto.setPreAveragePrice(Long.valueOf(averagePrice.substring(1)));
			}
			if (averagePrice.contains("-")) {
				String[] averagePriceArr = averagePrice.split("-");
				dto.setPreAveragePrice(Long.valueOf(averagePriceArr[0]));
				dto.setSufAveragePrice(Long.valueOf(averagePriceArr[1]));
			}
		}
		if (StringUtils.isNotBlank(acreage)) {
			if (acreage.contains("<=")) {
				dto.setSufAcreage(Long.valueOf(acreage.substring(2)));
			}
			if (acreage.contains(">")) {
				dto.setPreAcreage(Long.valueOf(acreage.substring(1)));
			}
			if (acreage.contains("-")) {
				String[] acreageArr = acreage.split("-");
				dto.setPreAcreage(Long.valueOf(acreageArr[0]));
				dto.setSufAcreage(Long.valueOf(acreageArr[1]));
			}
		}
		if(reqDto.getPremisesSaleStatus() != null){
			dto.setListSaleStatus(reqDto.getPremisesSaleStatus());
		}
		String accountType = pi.getAccountType();
		// 是否是管理员(0是 1否)
		if ("1".equals(accountType)) {
			// 非管理员,需添加业务员过滤.不能展示非此业务员驻守的楼盘
			dto.setPartnerId(pi.getId());
		}
		dto.setName(name);
		//项目总监或者项目经理可查看楼盘
        dto.setMobileTemp(pi.getPhone());
		dto.setOrders(
				"CASE WHEN al.main_push = 1 THEN NULL ELSE al.main_push END desc, CASE WHEN sequence IS NULL THEN 1 ELSE 0 END ASC," +
                        "sequence ASC,al.main_push_settime desc, al.premises_status asc,al.create_time desc ");
		Page<Premises> premises = premisesService.findPremisesByPartnerModel(dto, PageUtil.begin(pageNo, pageSize),
				pageSize);
		List<Premises> rows = premises.getRows();
		List<Long> premisesIds = new ArrayList<Long>();

		// 楼盘标签
		Set<Long> premisesLabel = new HashSet<>();
		for (Premises p : rows) {
			premisesIds.add(p.getId());
			if (StringUtils.isNotBlank(p.getCodeName())) {
				String[] codeNames = p.getCodeName().split(",");
				StringBuffer sb = new StringBuffer();
				for (String id : codeNames) {
					premisesLabel.add(Long.parseLong(id));
				}
			}
		}

        List<CaseMemberDto> listCaseMember = caseMemberService.getPremisesCMsmsList(premisesIds,pi.getHigherid());

		Map<Long, BaseCodeValue> baseCodeValueMap = baseCodeValueService.getMapWithIds(premisesLabel);

		// 查询楼盘信息
		Map<Long, Integer> mapPremisesCount = null;
		if (premisesIds != null && premisesIds.size() > 0) {
			PremisesRelationExternalDto preDto = new PremisesRelationExternalDto();
			preDto.setPremisesIds(premisesIds);
			mapPremisesCount = premisesRelationExternalService.getMapForPremisesCount(preDto);
		}
		List<PremisesDto> listDto = new ArrayList<PremisesDto>();
		for (Premises pre : rows) {
			if (StringUtils.isNotBlank(pre.getCodeName())) {
				String[] codeNames = pre.getCodeName().split(",");
				StringBuffer sb = new StringBuffer();
				for (String id : codeNames) {
					BaseCodeValue bcv = baseCodeValueMap.get(ParseUtils.toLong(id));
					if (null != bcv) {
						sb.append(bcv.getCodeName() + ",");
					}
				}
				if (sb.toString().length() > 0) {
					pre.setCodeName(sb.toString().substring(0, sb.toString().length() - 1));
				} else {
					pre.setCodeName("");
				}
				sb.setLength(0);
			}

            //驻场人员设为热线的人名为橘色
            if(listCaseMember != null && listCaseMember.size() > 0) {
                List<String> hotLinePartnerNameList = new ArrayList<>();
                for (CaseMemberDto caseMemberDto : listCaseMember) {
                    if(caseMemberDto.getPremisesId().equals(pre.getId()) && caseMemberDto.getPhoneStatus() != null
                            && caseMemberDto.getPhoneStatus().equals("1")) {
                        hotLinePartnerNameList.add(caseMemberDto.getAccountName());
                    }
                }
                if(hotLinePartnerNameList != null && hotLinePartnerNameList.size() > 0) {
                    String[] partnerNameArr = pre.getPartnerName().split(",");
                    String[] partnerNameArrTemp = partnerNameArr;
                    for (String partnerName : partnerNameArrTemp) {
                        for (String hotLinePartnerName : hotLinePartnerNameList) {
                            if(partnerName.equals(hotLinePartnerName)) {
                                partnerNameArr = (String[]) ArrayUtils.removeElement(partnerNameArr,partnerName);
                            }
                        }
                    }
                    pre.setPartnerName(StringUtils.join(partnerNameArr,","));
                    pre.setHotLinePartnerName(StringUtils.join(hotLinePartnerNameList,","));
                }

            }

			PremisesDto pDto = new PremisesDto();
			BeanUtils.copyProperties(pre, pDto);
			if (mapPremisesCount != null && mapPremisesCount.containsKey(pDto.getId())
					&& mapPremisesCount.get(pDto.getId()) > 0) {
				pDto.setSysId(ExternalSysEnum.V10.getCode());
			}
			// 清除大字段
			pDto.setFeature(null);
			pDto.setDiscount(null);
			pDto.setIntroduction(null);
			pDto.setSelling(null);
			pDto.setCustomer(null);
			pDto.setSaleSkill(null);
			pDto.setCorporateDesc(null);
			listDto.add(pDto);
		}
        // 默认设置了驻守人员且未设置案场热线则默认取最新的驻守人员为案场热线
        List<CaseMemberDto> listCaseMemberOrder = caseMemberService.getDistincPremisesCMList(premisesIds,pi.getHigherid());
		if(listCaseMemberOrder != null && listCaseMemberOrder.size() > 0) {
           for (PremisesDto premisesDto : listDto) {
                if (StringUtils.isNotBlank(premisesDto.getPartnerName()) && StringUtils.isBlank(premisesDto.getHotLinePartnerName())) {
                    String[] partnerNameArr = premisesDto.getPartnerName().split(",");
                    for (String partnerName : partnerNameArr) {
                        for (CaseMemberDto caseMemberDto : listCaseMemberOrder) {
                            if(partnerName.equals(caseMemberDto.getAccountName())) {
                                premisesDto.setHotLinePartnerName(partnerName);
                                List<String> tempList = new ArrayList(Arrays.asList(partnerNameArr));
                                tempList.remove(partnerName);
                                premisesDto.setPartnerName(StringUtils.join(tempList.toArray(),",",0,tempList.size()));
                                break;
                            }
                        }
                    }
                }
            }
        }

		Page<PremisesDto> page = new Page<>();
		page.setTotal(premises.getTotal());
		page.setPageSize(premises.getPageSize());
		page.setTotalPages(premises.getTotalPages());
		page.setPageNumber(premises.getPageNumber());
		page.setRows(listDto);

		resDto.setGetPremisesPage(page);
		resDto.setResult(ResultEnum.SUCCESS.getNo());
		return resDto;
	}

	/**
	 * 查询列表
	 *
	 * @param entity
	 *            搜索条件
	 * @return 分页记录
	 */
	@Override
	public List<Premises> selectListByDto(PremisesDto entity) {
		return premisesMapper.selectListByDto(entity);
	}

	/**
	 * @description
	 * @author sangtao
	 * @date 2017/12/5
	 * @param dto
	 **/
	@Override
	public GetPremisesForRuleResDto getPremisesForRule(GetPremisesForRuleReqDto dto) {
		GetPremisesForRuleResDto getPremisesForRuleResDto = new GetPremisesForRuleResDto();
		try {
			PartnerInfo info = partnerInfoService.selectById(Long.parseLong(dto.getUserId()));
			List<Premises> list = premisesService.getListForCommissionRule(info.getHigherid(),info.getAccountType(),info.getId());
			getPremisesForRuleResDto.setList(list);
			getPremisesForRuleResDto.setResult(ResultEnum.SUCCESS.getNo());
		} catch (Exception e) {
			logger.error("数据获取失败: {}", e);
			getPremisesForRuleResDto.setResult(ResultEnum.FAIL.getNo());
		}
		return getPremisesForRuleResDto;
	}

	@Override
	public GetAgentPremisesDynamicPageResDto getAgentPremisesDynamicPage(GetAgentPremisesDynamicPageReqDto reqDto) {
		GetAgentPremisesDynamicPageResDto res = new GetAgentPremisesDynamicPageResDto();
		if(StringUtils.isBlank(reqDto.getUserId())){
			return res;
		}
		PartnerInfo pi = partnerInfoService.selectById(Long.parseLong(reqDto.getUserId()));
		// 所有楼盘信息
		List<Long> premisesIds = new ArrayList<Long>();
		PremisesDto preDto = new PremisesDto();

		String domain = reqDto.getDomain();
        String companyUuid=reqDto.getCompanyUuid();
        String loginType = reqDto.getLoginType();
        if (StringUtils.isEmpty(domain) && StringUtils.isEmpty(companyUuid)) {
        	res.setResult(ResultEnum.FAIL.getNo());
        	res.setResultMsg("获取域名失败!");
            return res;
        }

        CompanyDto cDto = new CompanyDto();
        cDto.setDomain(domain);
        cDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
        cDto.setCompanyUuid(companyUuid);
        Company company = companyService.selectByDto(cDto);

		if (null!=company) {
			preDto.setCompanyId(company.getId());
		} else {
			res.setResult(ResultEnum.FAIL.getNo());
			res.setResultMsg("未找到相应楼盘");
			return res;
		}
		if (pi.getUserRoleId() != null
				&& Long.parseLong(PartnerInfoEnum.TOURIST_ROLE.getCode()) == pi.getUserRoleId()) {
			// 当前用户为游客时，展示该域名下的所有楼盘动态
			PremisesDto premisesDto = new PremisesDto();
			premisesDto.setCompanyId(company.getId());
			premisesDto.setPremisesStatus(PremisesStatusEnum.type1.getNo());
			premisesDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
			List<Premises> list = premisesService.selectListByDto(premisesDto);
			for (Premises pre : list) {
				premisesIds.add(pre.getId());
			}
		} else {
			// 在楼盘关系表中查询相关楼盘
			PremisesRelationDto relationDto = new PremisesRelationDto();
			relationDto.setDevCompanyId(company.getId());
			relationDto.setAgentCompanyId(pi.getHigherid());
			relationDto.setStatus(MechanismStatusEnum.enable.getNo());
			relationDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
			List<PremisesRelation> relation = premisesRelationService.selectListByDto(relationDto);
			// List<Long> premisesIds = new ArrayList<Long>();
			for (PremisesRelation pre : relation) {
				premisesIds.add(pre.getPremisesId());
			}
		}
		Integer pageNo = reqDto.getPageNo();
		Integer pageSize = reqDto.getPageSize();
		String premisesName = reqDto.getPremisesName();
		if (null == pageNo) {
			pageNo = 1;
		}
		if (null == pageSize) {
			pageSize = 10;
		}
		PremisesDynamicDto entity = new PremisesDynamicDto();
		if (StringUtils.isNotBlank(premisesName)) {
			entity.setPremisesName(premisesName);
		}
		if (premisesIds != null && premisesIds.size() > 0) {
			entity.setPremisesIds(premisesIds);
		}
		entity.setOrders("t.create_time desc, t.update_time desc");
		if(SystemIdEnum.WEAPP_AGENCY.getCode().equals(loginType)) {
			entity.setCanSee(true);
			entity.setOrders("t.update_time desc");
		}
		Page<PremisesDynamic> pageModel = premisesDynamicService.getPageModelNew(entity,
				PageUtil.begin(pageNo, pageSize), pageSize);
		pageModel.setPageSize(pageSize);
		pageModel.setPageNumber(pageNo);
		res.setResult(ResultEnum.SUCCESS.getNo());
		res.setPage(pageModel);
		return res;
	}
	
	/**
	 * 根据楼盘ID获取当前楼盘对应的接听电话的人员信息
	 * @param premisesIds
	 * @param premisesIds
	 * @return
	 * 	楼盘ID以及对应驻守咨询人的信息
	 */
	@Override
	public Map<Long, PartnerInfo> getPhoneCaseMemberInfoByPremisesInfo(List<Long> premisesIds){
		Map<Long, PartnerInfo> resMap = new HashMap<>();
		if(CollectionUtils.isEmpty(premisesIds)) {
			return resMap;
		}
		CaseMemberDto cmDto = new CaseMemberDto();
		cmDto.setPremisesIds(premisesIds);
		//cmDto.setPiStatus(MechanismStatusEnum.enable.getNo());
		cmDto.setOrders(" t.phone_status desc, t.create_time desc");
		//selectCaseMemberInfoByPremisesIds
		List<CaseMemberDto> cmDtoList = caseMemberService.selectCaseMemberInfoByPremisesIds(cmDto);
		if (null != cmDtoList && cmDtoList.size() > 0) {
			for (CaseMemberDto caseMemberDto : cmDtoList) {
				if(!resMap.containsKey(caseMemberDto.getPremisesId())) {
					PartnerInfo partnerInfo = new PartnerInfo();
					partnerInfo.setAccountName(caseMemberDto.getAccountName());
					partnerInfo.setPhone(caseMemberDto.getPhone());
					resMap.put(caseMemberDto.getPremisesId(), partnerInfo);
				}
			}
		}
		return resMap;
	}
	
	@Override
	public PremisesDynamic getAgentPremisesDynamicDetail(Long premisesDynamicId)  {
		PremisesDynamicDto entity = new PremisesDynamicDto();
		entity.setId(premisesDynamicId);
		List<PremisesDynamic> premisesDynamicList = premisesDynamicMapper.listPage(entity, 0, 1);
		if(CollectionUtils.isEmpty(premisesDynamicList)) {
			return null;
		}
		PremisesDynamic premisesDynamic = premisesDynamicList.get(0);
		List<Long> premisesIdList = new ArrayList<>();
		premisesIdList.add(premisesDynamic.getPremisesId());
		Map<Long, PartnerInfo> caseMemberMap = getPhoneCaseMemberInfoByPremisesInfo(premisesIdList);
		premisesDynamic.setCaseMemberPhone(caseMemberMap.get(premisesDynamic.getPremisesId()) == null? "": 
			caseMemberMap.get(premisesDynamic.getPremisesId()).getPhone());
		return premisesDynamic;
	}

	@Override
	public GetPremisesListByCompanyIdResDto getPremisesListByCompanyId(
			GetPremisesListByCompanyIdReqDto getPremisesListByCompanyIdReqDto) throws Exception {
		GetPremisesListByCompanyIdResDto resDto = new GetPremisesListByCompanyIdResDto();
		PartnerInfo pi = partnerInfoService.selectById(Long.valueOf(getPremisesListByCompanyIdReqDto.getUserId()));
		PremisesDto entity = new PremisesDto();
		entity.setCompanyId(pi.getHigherid());
		List<Premises> premises = premisesService.selectIdListByDto(entity);
		resDto.setResult(ResultEnum.SUCCESS.getNo());
		resDto.setPremisesList(premises);
		return resDto;
	}

	/**
	 * 判断是否M2楼盘
	 *
	 * @param reqDto
	 * @return
	 */
	@Override
	public GetChooseM2PremisesFlagResDto getChooseM2PremisesFlag(GetChooseM2PremisesFlagReqDto reqDto) {
		GetChooseM2PremisesFlagResDto resDto = new GetChooseM2PremisesFlagResDto();
		try {
			// 根据域名查询开发商
			CompanyDto cDto = new CompanyDto();
			cDto.setDomain(reqDto.getDomain());
			cDto.setCompanyUuid(reqDto.getCompanyUuid());
			// 0待审核1审核失败2审核成功
			cDto.setStatus(CheckStatusEnum.SUCCESS.getNo());
			cDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
			List<Company> list = companyService.selectListByDto(cDto);
			if (list == null || list.size() == 0) {
				resDto.setResult(ResultEnum.FAIL.getNo());
				resDto.setResultMsg("未找对应的开发商");
				return resDto;
			}
			String m2Flag = "F";
			if (StringUtils.isNotBlank(list.get(0).getMerchantCode())) {
				m2Flag = "T";
			}
			resDto.setM2Flag(m2Flag);
			resDto.setResult(ResultEnum.SUCCESS.getNo());
		} catch (Exception e) {
			logger.error("判断是否M2楼盘失败: {}", e);
		}
		return resDto;
	}

	/**
	 * 一二手联动获取楼盘信息
	 *
	 * @param dto
	 * @return
	 */
	@Override
	public GetPremisesForOtherResDto getPremisesListForOther(GetPremisesForOtherReqDto dto) {
		GetPremisesForOtherResDto resDto = new GetPremisesForOtherResDto();
		resDto.setResult(ResultEnum.SUCCESS.getNo());
		PremisesDto premisesDto = new PremisesDto();
		List<Long> devCompany = new ArrayList<Long>();
		devCompany.add(dto.getDevCompany());
		BeanUtils.copyProperties(dto, premisesDto);
		// 设置为一二手联动 公司id
		premisesDto.setDevCompanyIds(devCompany);
		if (StringUtils.isNotEmpty(dto.getHouseType())) {
			premisesDto.setApartmentType(dto.getHouseType());
		}

		if (dto.getAuditStatus() != null) {
			if (dto.getAuditStatus().compareTo(3l) == 0) {// 查询待申请记录，特殊处理
				premisesDto.setAuditStatus(null);
				premisesDto.setApply("1");
			}
			premisesDto.setV10CompanyUuid(dto.getV10CompanyUUid());
		}

		dto.setSort(StringUtils.isEmpty(dto.getSort()) ? " desc" : dto.getSort());
		String sort = dto.getSort();
		String orders = " t1.create_time+0 " + sort;
		// 开盘日期
		if ("10".equals(dto.getOrderType())) {
			orders = " t1.opening_time+0 " + sort;
		} else if ("20".equals(dto.getOrderType())) {
			// 均价
			orders = " t1.average_price+0 " + sort;
		}
		premisesDto.setOrders(orders);
		// 3.分销审核状态获取相应id
		DistributionAuditDto distributionAuditDto = new DistributionAuditDto();
		distributionAuditDto.setV10CompanyUUid(dto.getV10CompanyUUid());
		if (dto.getAuditStatus() != null) {
			distributionAuditDto.setAuditStatus(dto.getAuditStatus());
		}
		List<DistributionAudit> audits = distributionAuditMapper.selectListByDto(distributionAuditDto);
		Map<Long, DistributionAudit> auditMap = new HashMap<Long, DistributionAudit>();
		for (DistributionAudit dba : audits) {
			auditMap.put(dba.getPremisesId(), dba);
		}

		// 只加载已上架的楼盘
		premisesDto.setShelvesStatus(1l);
		int i = premisesMapper.selectPremisesCountForOther(premisesDto);
		resDto.setTotal(i);

		List<PremisesDto> listPremises;
		if (i == 0) {
			return resDto;
		}
		listPremises = premisesMapper.selectPremisesPageForOther(premisesDto,
				PageUtil.begin(dto.getPageNo(), dto.getPageSize()), dto.getPageSize());
		List<Long> ids = new ArrayList<>();
		for (PremisesDto pd : listPremises) {
			if (StringUtils.isNotEmpty(pd.getCodeName())) {
				String[] codeNames = pd.getCodeName().split(",");
				for (String s : codeNames) {
					ids.add(Long.parseLong(s));
				}
			}

			if (StringUtils.isNotBlank(pd.getCommission())) {
				JSONArray jsonArray = JSONObject.parseArray(pd.getCommission());
				if (jsonArray.size() > 0) {
					for (int ii = 0; ii < jsonArray.size(); ii++) {
						JSONObject jsonObject = jsonArray.getJSONObject(ii);
						if ("元".equals(jsonObject.getString("type"))) {
							pd.setCommission(jsonObject.getString("typeValue"));
							break;
						}
						if (ii == jsonArray.size() - 1 && "%".equals(jsonObject.getString("type"))) {
							pd.setCommission("");
							pd.setCommissionRate(jsonObject.getString("typeValue"));
						}
					}
				}
			}

			// 户型修改
			System.err.println(pd.getApartmentType());
			pd.setApartmentType(setHouseType(pd.getApartmentType()));
			pd.setAcreage(setAcreage(pd.getAcreage()));
			// 设置分销审核状态
			if (auditMap.containsKey(pd.getId())) {
				pd.setDistributionStatus(
						PremisesAuditEnum.getByCode(auditMap.get(pd.getId()).getAuditStatus().toString()).getName());
			} else {
				pd.setDistributionStatus(PremisesAuditEnum.PRMIISES_APPLY.getName());
			}
			Area city = areaService.selectById(pd.getCityId());
			Area area = areaService.selectById(pd.getAreaId());
			if (city != null && area != null) {
				pd.setFullAreaName(city.getName() + " " + area.getName());
			}
		}
		if (ids.size() == 0) {
			resDto.setData(listPremises);
			return resDto;
		}
		// 查询所有标签
		List<BaseCodeValue> listCodeValue = baseCodeValueService.selectWithIds(ids);
		Map<String, BaseCodeValue> map = new HashMap<String, BaseCodeValue>();
		for (BaseCodeValue bcv : listCodeValue) {
			map.put(bcv.getId().toString(), bcv);
		}
		// 匹配所有标签
		for (PremisesDto pd : listPremises) {
			if (StringUtils.isEmpty(pd.getCodeName())) {
				continue;
			}
			String[] codeNames = pd.getCodeName().split(",");
			StringBuilder stringBuilder = new StringBuilder();
			if (codeNames.length > 0) {
				for (String s : codeNames) {
					if (map.containsKey(s)) {
						stringBuilder.append(map.get(s).getCodeName() + ",");
					}
				}
				pd.setCodeName(stringBuilder.substring(0, stringBuilder.lastIndexOf(",")).toString());
			}

		}
		resDto.setData(listPremises);
		return resDto;
	}

	/**
	 * 一二手联动获取楼盘详情
	 *
	 * @param dto
	 * @return
	 */
	@Override
	public GetPremisesDetailForV10ResDto getPremisesDetailForV10(GetPremisesDetailForV10ReqDto dto) {
		GetPremisesDetailForV10ResDto resDto = new GetPremisesDetailForV10ResDto();
		Premises premises = premisesMapper.selectById(dto.getPremisesId());
		if (premises == null) {
			return null;
		}
		BeanUtils.copyProperties(premises, resDto);
		// 装修状况
		resDto.setDecorationType(DecorationTypeEnum.getNameByCode(resDto.getDecorationType()));
		// 省市区
		if (premises.getProvinceId() != null) {
			String province = areaService.selectById(premises.getProvinceId()).getName();
			resDto.setProvince(province);
		}
		if (premises.getCityId() != null) {
			String city = areaService.selectById(premises.getCityId()).getName();
			resDto.setCity(city);
		}
		if (premises.getAreaId() != null) {
			String area = areaService.selectById(premises.getAreaId()).getName();
			resDto.setArea(area);
		}
		if (StringUtils.isNotBlank(premises.getCommission())) {
			resDto.setCommission(premises.getCommission());
		}

		// 物业类型
		if (StringUtils.isNotEmpty(premises.getEstateType())) {
			resDto.setEstateType(EstateTypeEnum.getByIds(premises.getEstateType()));
		}
		if (StringUtils.isNotEmpty(premises.getBuildingType())) {
			String[] building = premises.getBuildingType().split(",");
			StringBuilder sb = new StringBuilder();
			for (String b : building) {
				sb.append(BuildingTypeEnum.getByNo(b).getDes() + ",");
			}

			resDto.setBuildingType(sb.substring(0, sb.lastIndexOf(",")));
		}

		// 报备保护时间
		resDto.setVisitProtectType("1".equals(premises.getVisitProtectType()) ? "天" : "分钟");
		if ("1".equals(premises.getVisitProtectType())) {
			resDto.setVisitProtect(new BigDecimal(premises.getVisitProtect()).divide(new BigDecimal(1440)).toString());
		}
		// 最短报备时间(默认分钟)
		resDto.setSpecialTime(premises.getSpecialTime());


		if (StringUtils.isNotEmpty(premises.getCommissionWay())) {
			resDto.setCommissionWay(premises.getCommissionWay().equals("1") ? "签约结佣" : "按揭结佣");
		}
		// 销售状态
		if (StringUtils.isNotEmpty(premises.getSaleStatus())) {
			resDto.setSaleStatus(SaleStatusEnum.getByNo(premises.getSaleStatus()).getDes());
		}
		// 楼盘标签
		if (StringUtils.isNotEmpty(premises.getCodeName())) {
			String[] labels = premises.getCodeName().split(",");
			if (labels.length > 0) {
				List<Long> lableList = new ArrayList<Long>();
				for (String b : labels) {
					lableList.add(Long.parseLong(b));
				}
				List<BaseCodeValue> codes = baseCodeValueService.selectWithIds(lableList);
				StringBuilder sbCodes = new StringBuilder();
				for (BaseCodeValue bcv : codes) {
					sbCodes.append(bcv.getCodeName() + ",");
				}
				resDto.setPremisesLabel(sbCodes.substring(0, sbCodes.lastIndexOf(",")));
			}
		}

		// 楼盘地址
		resDto.setPremisesAddress(premises.getPremisesAddress());
		// 入住时间
		resDto.setCheckInTime(premises.getFormatCheckInTime());
		// 开盘时间
		resDto.setOpeningTime(premises.getFormatOpeningTime());
		// 合作有效期
		resDto.setCooperationTimeBegin(premises.getFormatCooperationBeginTime());
		resDto.setCooperationTimeEnd(premises.getFormatCooperationEndTime());
		resDto.setHuXingArea(getPremisesArea(dto.getPremisesId()));
		return resDto;
	}

	/**
	 *
	 * 功能描述: <br>
	 * 获得楼盘户型中的最大值 跟最小值
	 *
	 * @param id
	 * @return
	 * @see [相关类/方法](可选)
	 * @since [产品/模块版本](可选)
	 */
	public String getPremisesArea(Long id) {
		String result = "0~0㎡";
		ApartmentLayoutDiagramDto entity = new ApartmentLayoutDiagramDto();
		entity.setPremisesId(id);
		entity.setOrders(" t.area+1 desc");
		List<ApartmentLayoutDiagram> list = apartmentLayoutDiagramService.selectListByDto(entity);
		if (list != null && !list.isEmpty()) {
			return list.get(list.size() - 1).getArea() + "~" + list.get(0).getArea() + "㎡";
		}
		return result;
	}

	/**
	 * v10接口 设置户型
	 *
	 * @param old
	 * @return
	 */
	private String setHouseType(String old) {
		StringBuilder sb = new StringBuilder();
		if (StringUtils.isEmpty(old)) {
			return old;
		}
		String[] values = old.split(",");
		if (values.length == 0) {
			return old;
		}
		// 去重
		Set<String> sets = new HashSet<String>();
		for (String s : values) {
			String[] temp = s.split("室");
			if (temp.length != 0) {
				sets.add(temp[0]);
			}
		}
		for (String name : sets) {
			try {
				sb.append(Integer.parseInt(name)).append("室/");
			} catch (NumberFormatException e) {

			}
		}
		if (sets.size() > 0 && sb.lastIndexOf("/") != -1) {
			return sb.substring(0, sb.lastIndexOf("/"));
		}
		return sb.toString();
	}

	/**
	 * 设置户型
	 *
	 * @param areas
	 * @return
	 */
	private List<Layout> setHouseTypeList(List<ApartmentLayoutDiagram> areas) {
		List<Layout> list = new ArrayList<>();
		if (areas == null || areas.size() == 0) {
			return list;
		}
		for (ApartmentLayoutDiagram ald : areas) {
			Layout layout = new Layout();
			layout.setArea(ald.getArea());
			layout.setUrl(ald.getUrl());
			layout.setApartment(getApartments(ald.getApartmentLayout()));
			list.add(layout);
		}
		return list;
	}

	/**
	 * v10接口 设置户型平米数
	 *
	 * @param acreage
	 * @return
	 */
	private String setAcreage(String acreage) {
		double min = 0;
		double max = 0;
		if (StringUtils.isEmpty(acreage)) {
			return acreage;
		}
		String[] values = acreage.split(",");
		if (values.length <= 1) {
			return acreage;
		}
		StringBuilder sb = new StringBuilder();
		if (StringUtils.isNotBlank(values[0])) {
			min = Double.parseDouble(values[0]);
			max = min;
			for (String s : values) {
				double temp = Double.parseDouble(s);
				if (temp < min) {
					min = temp;
				}
				if (temp > max) {
					max = temp;
				}
			}
			sb.append(min).append("~").append(max);
		}

		return sb.toString();
	}

	/**
	 * 设置户型
	 *
	 * @param aprtment
	 * @return
	 */
	private String[] getApartments(String aprtment) {
		String[] returnStrings = new String[4];
		String[] s = aprtment.indexOf("卧室")!=-1?aprtment.split("卧室"):aprtment.split("室");
		if (s.length > 0) {
			returnStrings[0] = s[0].equals("无") ? "" : s[0];
			if (s.length == 1) {
				return returnStrings;
			}
		}
		String[] t = s[1].split("厅");
		if (s.length > 0) {
			returnStrings[1] = t[0].equals("无") ? "" : t[0];
			if (t.length == 1) {
				return returnStrings;
			}
		}
		String[] w = t[1].indexOf("卫生间")!=-1?t[1].split("卫生间"):t[1].split("卫");
		if (w.length > 0) {
			returnStrings[2] = w[0].equals("无") ? "" : w[0];
			if (w.length == 1) {
				return returnStrings;
			}
		}
		String[] yt = w[1].split("阳台");
		if (yt.length > 0) {
			returnStrings[3] = yt[0].equals("无") ? "0" : yt[0];
			return returnStrings;
		}

		return null;
	}

	/**
	 * 开发商楼盘列表
	 *
	 * @param reqDto
	 * @return
	 */
	@Override
	public GetDevPremisesPageResDto getDevPremisesPage(GetDevPremisesPageReqDto reqDto) {
		GetDevPremisesPageResDto resDto = new GetDevPremisesPageResDto();
		int pageNo = reqDto.getPageNo();
		int pageSize = reqDto.getPageSize();

		String companyUuid=reqDto.getCompanyUuid();
		String domain=reqDto.getDomain();
        if (StringUtils.isEmpty(domain) && StringUtils.isEmpty(companyUuid)) {
        	resDto.setResult(ResultEnum.FAIL.getNo());
        	resDto.setResultMsg("获取公司信息失败!");
            return resDto;
        }

        // 根据域名或者公司uuid查询开发商
		CompanyDto cDto = new CompanyDto();
	    cDto.setDomain(domain);
	    cDto.setStatus(CheckStatusEnum.SUCCESS.getNo());
	    cDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
	    cDto.setCompanyUuid(companyUuid);
	    Company company = companyService.selectByDto(cDto);

	    if (null == company) {
            //此处为商户不存在
	    	resDto.setResult(ResultEnum.FAIL.getNo());
	    	resDto.setResultMsg("未获取到开发商信息!");
            return resDto;
        }
		Long companyId = company.getId();

		// 查询合作机构
		PremisesDto entity = new PremisesDto();
		entity.setCompanyId(companyId);
		if (StringUtils.isNotBlank(reqDto.getName())) {
			entity.setName(reqDto.getName());
		}
		if (reqDto.getProvinceId() != null) {
			entity.setProvinceId(reqDto.getProvinceId());
		}
		if (reqDto.getCityId() != null) {
			entity.setCityId(reqDto.getCityId());
		}
		if (reqDto.getAreaId() != null) {
			entity.setAreaId(reqDto.getAreaId());
		}
		if (StringUtils.isNotBlank(reqDto.getEstateType())) {
			entity.setEstateType(reqDto.getEstateType());
		}
		entity.setPremisesStatus(PremisesStatusEnum.type1.getNo());
		// 在售状态
		entity.setSaleStatus(SaleStatusEnum.type_1.getNo());
		entity.setOrders(
                "CASE WHEN t.main_push = 1 THEN NULL ELSE t.main_push END desc, CASE WHEN t.sequence IS NULL THEN 1 ELSE 0 END ASC," +
                        "t.sequence ASC,t.main_push_settime desc, t.premises_status asc,t.create_time desc ");
		String averagePrice = reqDto.getAveragePrice();
		if (StringUtils.isNotBlank(averagePrice)) {
			// 避免查询条件混淆
			entity.setAveragePrice(null);
			if (averagePrice.contains("<=")) {
				entity.setSufAveragePrice(Long.valueOf(averagePrice.substring(2)));
			}
			if (averagePrice.contains(">")) {
				entity.setPreAveragePrice(Long.valueOf(averagePrice.substring(1)));
			}
			if (averagePrice.contains("-")) {
				String[] averagePriceArr = averagePrice.split("-");
				entity.setPreAveragePrice(Long.valueOf(averagePriceArr[0]));
				entity.setSufAveragePrice(Long.valueOf(averagePriceArr[1]));
			}
		}

		String acreage = reqDto.getAcreage();
		if (StringUtils.isNotBlank(acreage)) {
			if (acreage.contains("<=")) {
				entity.setSufAcreage(Long.valueOf(acreage.substring(2)));
			}
			if (acreage.contains(">")) {
				entity.setPreAcreage(Long.valueOf(acreage.substring(1)));
			}
			if (acreage.contains("-")) {
				String[] acreageArr = acreage.split("-");
				entity.setPreAcreage(Long.valueOf(acreageArr[0]));
				entity.setSufAcreage(Long.valueOf(acreageArr[1]));
			}
		}
		if (reqDto.getCityId() != null && reqDto.getCityId() != 0) {
			entity.setCityId(reqDto.getCityId());
		}
		Page<PremisesDto> page = premisesService.getPageModelByAcreage(entity, PageUtil.begin(pageNo, pageSize), pageSize);

		List<PremisesDto> premisesList = page.getRows();
		if (null != premisesList && premisesList.size() > 0) {
			for (PremisesDto premises : premisesList) {
				String key = String.valueOf(premises.getId());
				String value = "0";
				premises.setReportCount(value);

				// 从楼盘中获取佣金、带看奖、结佣方式
				String commission = premises.getCommission();
				String reward = premises.getReward();
				String way = premises.getCommissionWay();
				premises.setCommission(commission);
				premises.setReward(reward);
				if (StringUtils.isNotBlank(way) && !"0".equals(way)) {
					premises.setCommissionWay(CommissionWayEnum.getDescByNo(way));
				} else {
					// 可能采用新增合作机构的结佣方式，但是之前的楼盘结佣方式有影响
					premises.setCommissionWay("");
				}
			}
		}

		resDto.setGetAgentPremisesPage(page);
		resDto.setResult(ResultEnum.SUCCESS.getNo());
		return resDto;
	}

	/**
	 * 获取案场人员信息
	 * @param reqDto
	 * @return
	 */
	public GetPremisesCMSmsPageResDto getPremisesCMSmsPage(GetPremisesCMSmsPageReqDto reqDto){
		GetPremisesCMSmsPageResDto resDto = new GetPremisesCMSmsPageResDto();
		// 查询合作机构
		PartnerInfo pi = partnerInfoService.selectById(stringToLong(reqDto.getUserId()));
		if (pi == null) {
			resDto.setResult(ResultEnum.FAIL.getNo());
			resDto.setResultMsg("未获取到登陆人员信息");
			return resDto;
		}

		//获取公司信息
		CompanyDto companyDto = new CompanyDto();
		if(StringUtils.isNotEmpty(reqDto.getCompanyUuid())){
			companyDto.setCompanyUuid(reqDto.getCompanyUuid());
		}else{
			companyDto.setDomain(reqDto.getDomain());
		}
		Company company = companyService.selectByDto(companyDto);
		if(company == null){
			resDto.setResult(ResultEnum.FAIL.getNo());
			resDto.setResultMsg("未获取到渠道商信息");
			return resDto;
		}


		List<PremisesCMSmsDto> list = new ArrayList<>();
		//获取楼盘列表,设置查询条件
		PremisesDto premisesDto = new PremisesDto();
		premisesDto.setCompanyId(company.getId());
		premisesDto.setName(reqDto.getPremisesName());
		premisesDto.setEstateType(reqDto.getEstateType());
		premisesDto.setProvinceId(reqDto.getProvinceId());
		premisesDto.setCityId(reqDto.getCityId());
		premisesDto.setAreaId(reqDto.getAreaId());
		//楼盘审核通过
		premisesDto.setPremisesStatus(PremisesAuditEnum.PRMIISES_SUCCESS.getCode());
		//销售状态为  1：在售
		premisesDto.setSaleStatus(SaleStatusEnum.type_1.getNo());
        premisesDto.setCaseMemberName(reqDto.getCaseMemberName());

		String accountType = pi.getAccountType();
		// 是否是管理员(0是 1否)
		if ("1".equals(accountType)) {
			// 非管理员,需添加业务员过滤.不能展示非此业务员驻守的楼盘
			premisesDto.setPartnerId(pi.getId());
		}
		int count = premisesMapper.findPremisesByPartnerCount(premisesDto);
		premisesDto.setOrders(
				" CASE WHEN sequence IS NULL THEN 1 ELSE 0 END ASC,sequence ASC, premises_status asc, create_time desc ");
		List<Premises> premisesList = premisesMapper.findPremisesByPartnerList(premisesDto,PageUtil.begin(reqDto.getPageNo(),reqDto.getPageSize()),reqDto.getPageSize());
		if(premisesList == null || premisesList.size() == 0){
			return resDto;
		}

		List<Long> premisesIds = premisesList.stream().map(Premises::getId).collect(Collectors.toList());

		List<CaseMemberDto> listCaseMember = caseMemberService.getPremisesCMsmsList(premisesIds,company.getId());
		//组织数据
		Map<Long,List<CaseMemberDto>> map = new HashMap<>();
		for(CaseMemberDto c : listCaseMember){
			if(map.containsKey(c.getPremisesId())){
				map.get(c.getPremisesId()).add(c);
			}else{
				map.put(c.getPremisesId(),new ArrayList<CaseMemberDto>(){{add(c);}});
			}
		}

		for(Premises p : premisesList){
			PremisesCMSmsDto dto = new PremisesCMSmsDto();
			dto.setPremisesId(p.getId());
			dto.setCaseMember(map.containsKey(p.getId()) ? map.get(p.getId()) :  new ArrayList<>());
			dto.setPremisesName(p.getName());
			dto.setCaseMemberNum(map.get(p.getId()) == null ? 0 : map.get(p.getId()).size());
			dto.setManager(p.getManager());
			list.add(dto);
		}
		resDto.setList(list);
		resDto.setTotal(count);
		resDto.setPageNo(reqDto.getPageNo());
		return resDto;
	}

	@Override
	public BatchAssignPremisesAgentResDto batchAssignPremisesAgent(BatchAssignPremisesAgentReqDto reqDto) {
	    if(StringUtils.isBlank(reqDto.getAgentIds())) {
	        throw new TServerException("请选择分销商！");
        }
		BatchAssignPremisesAgentResDto resDto = new BatchAssignPremisesAgentResDto();
		List<Long> premisesIds = reqDto.getPremisesIds();
		for (Long premisesId : premisesIds) {
			// 先将原有楼盘的合作的经纪公司的Status都置为无效
			PremisesRelationDto entity = new PremisesRelationDto();
			entity.setPremisesId(premisesId);
            List<String> oldAgencyIdList = getOldAgencyIds(entity);
			// 获取原关系表ID
			String oldIds = getOldIds(entity);
			if (StringUtils.isNotBlank(oldIds)) {
				PremisesRelationDto dto = new PremisesRelationDto();
				dto.setStatus(MechanismStatusEnum.disable.getNo());
				premisesRelationService.updates(dto, oldIds);
			}
			// 将选中的经纪公司的status再置为有效
			if (StringUtils.isNotBlank(reqDto.getAgentIds())) {
				PremisesRelationDto relationDto = new PremisesRelationDto();
				relationDto.setStatus(MechanismStatusEnum.enable.getNo());
				relationDto.setPremisesId(premisesId);
				premisesRelationService.editsByIdsAndpremisesIds(relationDto, reqDto.getAgentIds());
			}
			//发送给分销管理员

            if(SaleStatusEnum.type_1.getNo().equals(reqDto.getPremisesSaleStatus()) && PremisesStatusEnum.type1.getNo().equals(reqDto.getPremisesStatus())) {
                //获取需要推送微信消息的分销商
                // 只发送给新增加的
                List<String> newIdList = new ArrayList<>(Arrays.asList(reqDto.getAgentIds().split(",")));
                if(oldAgencyIdList != null && oldAgencyIdList.size() > 0) {
                    newIdList.removeAll(oldAgencyIdList);
                }
                sendWeixinMsgWithBatchAssignPremises(premisesId, StringUtils.join(newIdList,","), reqDto.getAgencyAccessToken(),  reqDto.getCompanyUuid(),  reqDto.getDomain());
            }
		}
		resDto.setResult(ResultEnum.SUCCESS.getNo());
		return resDto;
	}

	@Override
	public ChangeShelvesStatusResDto changeShelvesStatus(ChangeShelvesStatusReqDto reqDto) {
		ChangeShelvesStatusResDto resDto = new ChangeShelvesStatusResDto();

		if (null == reqDto.getId()) {
			resDto.setResult(ResultEnum.FAIL.getNo());
			resDto.setResultMsg("上下架失败!");
			return resDto;
		}

		PremisesDto entity = new PremisesDto();
		entity.setId(reqDto.getId());
		entity.setShelvesStatus(Long.valueOf(reqDto.getShelvesStatus()));
		int updateRow = premisesService.changeShelvesStatus(entity);
		if (updateRow < 0) {
			resDto.setResult(ResultEnum.FAIL.getNo());
			resDto.setResultMsg("上下架失败!");
			return resDto;
		}

		resDto.setResult(ResultEnum.SUCCESS.getNo());
		return resDto;
	}

	@Override
	public GetPremisesCityResDto getPremisesCity(GetPremisesCityReqDto reqDto) {
		GetPremisesCityResDto resDto = new GetPremisesCityResDto();
		List<CityGroupDto> list = premisesService.getPremisesCityList(reqDto.getCurrentCity());
		resDto.setData(list);
		return resDto;
	}

	@Override
	public GetPremisesCityResDto getPremisesCityGroupByPinyin(String currentCity, PremisesDto reqDto) {
		GetPremisesCityResDto resDto = new GetPremisesCityResDto();
		List<CityGroupDto> list = premisesService.getPremisesCityGroupByPinyin(currentCity, reqDto);
		resDto.setData(list);
		return resDto;
	}

	@Override
	public GetPremisesListPageResDto getPremisesListPage(GetPremisesListPageReqDto reqDto) {
		GetPremisesListPageResDto resDto = new GetPremisesListPageResDto();
		int pageNo = PageUtil.begin(reqDto.getPageNo(), reqDto.getPageSize());
		reqDto.setPageNo(pageNo);
		if (StringUtils.isEmpty(reqDto.getV10CompanyUuid())) {
			resDto.setResponseCode(ResultEnum.FAIL.getNo());
			resDto.setResponseMessage("公司ID不能为空!");
			return resDto;
		}
		PremisesExtDto extDTO = new PremisesExtDto();
		BeanUtils.copyProperties(reqDto, extDTO);
		OrderPropertyEnum orderProperty = OrderPropertyEnum.getByNo(extDTO.getOrderProperty());
		extDTO.setHouseType(HuxingEnum.getNameByCode(extDTO.getHouseType()));
		if (orderProperty == null) {
			extDTO.setOrders(OrderPropertyEnum.ORDER_PROPERTY_10.getName());
			extDTO.setSort(OrderPropertyEnum.ORDER_PROPERTY_10.getSort());
		} else {
			extDTO.setOrders(orderProperty.getName());
			extDTO.setSort(orderProperty.getSort());
		}
		Page<PremisesViewDto> page = premisesService.getPremisesViewList(extDTO);
		PremisesPageResponse data = new PremisesPageResponse();
		data.setList(page.getRows());
		data.setTotalCount(page.getTotal());
		data.setTotalPage(page.getTotalPages());
		resDto.setData(data);
		return resDto;
	}

	@Override
	public GetPremisesPhotoResDto getPremisesPhotoList(Long premisesId) {
		GetPremisesPhotoResDto resDTO = new GetPremisesPhotoResDto();
		Premises premises = premisesMapper.selectById(premisesId);
		if (premises != null) {
			List<PremisesPhotoDto> premisesPhotoList = premisesImageService.selectPremisesPhono(premisesId);
			if (premisesPhotoList != null && !premisesPhotoList.isEmpty()) {
				premisesPhotoList.forEach(item -> {
					PremisesImageEnum image = PremisesImageEnum.getByNo(item.getPhotoType());
					if (image != null) {
						item.setPhotoName(image.getName());
					}
					item.setPhotoList(stringToList(item.getPhotoListStr()));
				});
				resDTO.setData(premisesPhotoList);
			} else {
				return resDTO;
			}
		}
		return resDTO;
	}

	/**
	 * String转List
	 *
	 * @param str
	 * @return
	 */
	public List<String> stringToList(String str) {
		if (!StringUtils.isEmpty(str)) {
			return Arrays.asList(str.split(","));
		}
		return null;
	}

	@Override
	public GetPremisesHuxingResDto getPremisesHuxingList(Long premisesId) {
		GetPremisesHuxingResDto resDTO = new GetPremisesHuxingResDto();
		List<PremisesHuxingResultDto> data = new ArrayList<>();
		List<PremisesHuxingDto> list = apartmentLayoutDiagramService.selectHuxingByPremisesId(premisesId);
		if (list != null && !list.isEmpty()) {
			for (HuxingEnum huxing : HuxingEnum.values()) {
				PremisesHuxingResultDto result = new PremisesHuxingResultDto();
				List<PremisesHuxingDto> huxingList = list.stream()
						.filter(h -> h.getGroupProperty().equals(huxing.getNo())).collect(Collectors.toList());
				if (!huxingList.isEmpty()) {
					Long count = list.stream().filter(h -> h.getGroupProperty().equals(huxing.getNo())).count();
					result.setGroupCount(count);
					result.setGroupName(huxing.getDes());
					result.setHuXingList(huxingList);
					data.add(result);
				}
			}
			resDTO.setData(data);
		}
		return resDTO;
	}

	public String getDomainName() {
		return domainName;
	}

	/**
	 * 设置楼盘顺序包含 置顶 调整楼盘顺序
	 * 置顶和调整楼盘顺序都可能会影响到整个楼盘顺序，所以每次操作都涉及到商户的所有楼盘顺序
	 */
	public SetPremisesOrderResDto setPremisesOrder(SetPremisesOrderReqDto reqDto){
        SetPremisesOrderResDto resDto = new SetPremisesOrderResDto();
		//楼盘操作 置顶，

        // 查询合作机构
        PartnerInfo pi = partnerInfoService.selectById(stringToLong(reqDto.getUserId()));
        if (pi == null) {
            resDto.setResult(ResultEnum.FAIL.getNo());
            resDto.setResultMsg("未获取到合作机构!");
            return resDto;
        }
        //1 获取该商户下所有楼盘然后进行排序操作
        PremisesDto premisesDto = new PremisesDto();
        premisesDto.setCompanyId(pi.getHigherid());
		List<Premises> premisesList = premisesMapper.selectPremisesOrder(premisesDto);
		//2.排序
        premisesList = setOrder(reqDto.getOpType(), reqDto.getPremisesIds(), premisesList);
		//3.更新
        premisesMapper.setPremisesOrder(premisesList);
        resDto.setResult(ResultEnum.SUCCESS.getNo());
        return resDto;
	}

    @Override
    public CheckPremisesNameResDto checkPremisesName(CheckPremisesNameReqDto reqDto1) {
	    if(StringUtils.isBlank(reqDto1.getPremisesName())) {
	        throw new TServerException("楼盘名称不能为空！");
        }
        CheckPremisesNameResDto resDto = new CheckPremisesNameResDto();
        resDto.setResult(ResultEnum.SUCCESS.getNo());

        PremisesDto dto = new PremisesDto();
        dto.setCompanyId(reqDto1.getMerchantId());
	    dto.setName(reqDto1.getPremisesName());
	    if(reqDto1.getPremisesId() != 0) dto.setId(reqDto1.getPremisesId());
	    dto.setDelFlag(DelFlagEnum.UNDEL.getNo());
        List<Premises> list = premisesMapper.checkPremisesName(dto);
        if(list != null && list.size() > 0) {
            //百分百匹配才算重复，只取一个就好
            resDto.setPremisesNames(list.get(0).getName());
        }
        return resDto;
    }

    private List<Premises> setOrder(int opType, List<Long> premisesIds, List<Premises> premisesList) {
        if(opType == 1) {
            //置顶
            List<Premises> topItems = new ArrayList<>(premisesIds.size());
            for (Premises premises : premisesList) {
                for (Long premisesId : premisesIds) {
                    if(premises.getId().equals(premisesId)) {
                        topItems.add(premises);
                    }
                }
            }
            premisesList.removeAll(topItems);
            premisesList.addAll(0, topItems);
            for (int i = 0; i < premisesList.size(); i++) {
                Premises premises = premisesList.get(i);
                premises.setSequence(i+1);
            }
        } else if (opType == 2 || opType == 3) {
            //判断是否符合需求
            if(premisesIds != null && premisesIds.size() > 1) {
                throw new TServerException("只支持单个楼盘移动");
            }
            //重新设置排序字段
            for (int i = 0; i < premisesList.size(); i++) {
                Premises premises = premisesList.get(i);
                premises.setSequence(i+1);
            }

            //获取要移动对象位置
            int currIndex = 0;
            for (Long premisesId : premisesIds) {
                for (int i = 0; i < premisesList.size(); i++) {
                     Premises premises = premisesList.get(i);
                    if(premisesId.equals(premises.getId())) {
                        currIndex = i;
                        break;
                    }
                }
            }
            Premises currPremises = premisesList.get(currIndex);
            if(opType == 2) {
                //上移
                if(currIndex == 0) {
                    throw new TServerException("楼盘已被移至列表的最上方");
                }
                currPremises.setSequence(currPremises.getSequence()-1);
                Premises prePremises = premisesList.get(currIndex-1);
                prePremises.setSequence(prePremises.getSequence()+1);
            } else {
                //下移
                if(currIndex == (premisesList.size()-1)) {
                    throw new TServerException("楼盘已被移至列表的最下方");
                }
                currPremises.setSequence(currPremises.getSequence()+1);
                Premises backPremises = premisesList.get(currIndex+1);
                backPremises.setSequence(backPremises.getSequence()-1);
            }
        }
        return premisesList;
    }

	/**
	 * 设置主推楼盘  或取消
	 * @param reqDto
	 * @return
	 */
	@Override
    public SetMainPushPremisesResDto setMainPushPremises(SetMainPushPremisesReqDto reqDto){
		SetMainPushPremisesResDto resDto = new SetMainPushPremisesResDto();

		PremisesDto dto = new PremisesDto();
		dto.setId(reqDto.getPremisesId());
		dto.setMainPush(reqDto.getMainPush());
		try {
			premisesService.updateMainPushPremises(dto);
			resDto.setResult(ResultEnum.SUCCESS.getNo());
		}catch (Exception e){
			resDto.setResult(ResultEnum.FAIL.getNo());
		}

		return resDto;
	}

    @Override
    public PremisesTypeCountResDto premisesTypeCount(CommonReqDTO reqDto) {
        // 查询合作机构
        PartnerInfo pi = partnerInfoService.selectById(stringToLong(reqDto.getUserId()));
        if (pi == null) {
            throw new TServerException("未获取到合作机构！");
        }

        PremisesTypeCountResDto resDto = new PremisesTypeCountResDto();
        PremisesDto dto = new PremisesDto();
        dto.setCompanyId(pi.getHigherid());
        String accountType = pi.getAccountType();
        // 是否是管理员(0是 1否)
        if ("1".equals(accountType)) {
            // 非管理员,需添加业务员过滤.不能展示非此业务员驻守的楼盘
            dto.setPartnerId(pi.getId());
        }
        dto.setMobileTemp(pi.getPhone());
        //在售
        dto.setSaleStatus(SaleStatusEnum.type_1.getNo());
        dto.setPremisesStatus(PremisesStatusEnum.type1.getNo());
        int onSaleCount = premisesMapper.premisesTypeCount(dto);
        //待售
        dto.setPremisesStatus(PremisesStatusEnum.type1.getNo());
        dto.setSaleStatus(SaleStatusEnum.type_0.getNo());
        int forSaleCount = premisesMapper.premisesTypeCount(dto);
        //待审核
        dto.setPremisesStatus(PremisesStatusEnum.type0.getNo());
        dto.setSaleStatus(null);
        int beCheckCount = premisesMapper.premisesTypeCount(dto);
        //售罄
        dto.setPremisesStatus(PremisesStatusEnum.type1.getNo());
        dto.setSaleStatus(SaleStatusEnum.type_2.getNo());
        int sellOutCount = premisesMapper.premisesTypeCount(dto);
        //下架
        dto.setPremisesStatus(PremisesStatusEnum.type1.getNo());
        dto.setSaleStatus(SaleStatusEnum.type_3.getNo());
        int lowerShelfCount = premisesMapper.premisesTypeCount(dto);
        //审核失败
        dto.setPremisesStatus(PremisesStatusEnum.type2.getNo());
        dto.setSaleStatus(null);
        int checkFailCount = premisesMapper.premisesTypeCount(dto);
        resDto.setOnSaleCount(onSaleCount);
        resDto.setForSaleCount(forSaleCount);
        resDto.setBeCheckCount(beCheckCount);
        resDto.setSellOutCount(sellOutCount);
        resDto.setLowerShelfCount(lowerShelfCount);
        resDto.setCheckFailCount(checkFailCount);
        resDto.setResult(ResultEnum.SUCCESS.getNo());
        return resDto;
    }

	/**
	 * 修改楼盘销售状态及审核状态时推送消息
	 * @param agencyAccessToken
	 * @param companyUuid
	 * @param domain
	 * @param premisesId
	 * @param oldSaleStatus
	 * @param newSaleStatus
	 * @param auditStatus
	 */
	@Async
	@Override
    public void sendWeixinMsgWithPremises(String agencyAccessToken, String companyUuid, String domain, String premisesId,String oldSaleStatus,String newSaleStatus,String auditStatus){
		//获取楼盘执行分销商
//		if(PremisesStatusEnum.type2.getNo().equals(auditStatus) && SaleStatusEnum.type_1.getNo().equals(newSaleStatus)){
//			//上架场景2 楼盘上架：楼盘已指定分销商，楼盘审核通过，但状态不为在售 新状态为在售
//			wxTemplateMsgService.sendPremisesShelveTemplateMsg(agencyAccessToken,companyUuid,domain,premisesId);
//		}else
		 if(SaleStatusEnum.type_1.getNo().equals(oldSaleStatus) && !SaleStatusEnum.type_1.getNo().equals(newSaleStatus)){
			//下架场景2：楼盘下架：楼盘为在售状态 --> 保存为：待售、售罄、下架的状态后给所有指定分销商推送
			wxTemplateMsgService.sendPremisesUnshelveTemplateMsg(agencyAccessToken,companyUuid,domain,premisesId,SaleStatusEnum.getByNo(newSaleStatus).getDes());
		}else if(SaleStatusEnum.type_1.getNo().equals(oldSaleStatus) && !SaleStatusEnum.type_1.getNo().equals(newSaleStatus)){
            //下架场景2：楼盘下架：楼盘为在售状态且审核通过 --> 编辑后为待审核状态给所有指定分销商推送
            wxTemplateMsgService.sendPremisesUnshelveTemplateMsg(agencyAccessToken,companyUuid,domain,premisesId,PremisesStatusEnum.getByNo(auditStatus).getDes());
        }else if(PremisesStatusEnum.type1.getNo().equals(auditStatus) && !SaleStatusEnum.type_1.getNo().equals(oldSaleStatus)&& SaleStatusEnum.type_1.getNo().equals(newSaleStatus)){
			//楼盘上架：楼盘已指定分销商，楼盘审核通过，但状态不为在售 楼盘交易状态改为在售后推送给所有指定分销商推送
			wxTemplateMsgService.sendPremisesShelveTemplateMsg(agencyAccessToken,companyUuid,domain,premisesId);
		}
	}

	/**
	 * 楼盘审核操作推送消息，在售审核成功 上架消息，在售审核失败下架消息
	 * @param agencyAccessToken
	 * @param companyUuid
	 * @param domain
	 * @param premisesId
	 * @param oldAuditStatus
	 * @param newAuditStatus
	 * @param saleStatus
	 */
	@Async
	@Override
	public void sendWeixinMsgWithPremisesAudit(String agencyAccessToken, String companyUuid, String domain, String premisesId,String oldAuditStatus,String newAuditStatus,String saleStatus){
		//上架场景1： 状态为在售:楼盘已指定分销商，但楼盘未审核通过，楼盘审核通过后推送给所有指定分销商推送
		if(SaleStatusEnum.type_1.getNo().equals(saleStatus) && PremisesStatusEnum.type1.getNo().equals(newAuditStatus) && !PremisesStatusEnum.type1.getNo().equals(oldAuditStatus)){
			wxTemplateMsgService.sendPremisesShelveTemplateMsg(agencyAccessToken,companyUuid,domain,premisesId);
		}else if(SaleStatusEnum.type_1.getNo().equals(saleStatus) && PremisesStatusEnum.type1.getNo().equals(oldAuditStatus) && PremisesStatusEnum.type2.getNo().equals(newAuditStatus)){
			//下架场景1：（楼盘审核状态）楼盘下架：楼盘为在售状态 --> 保存为：审核不通过的状态后给所有指定分销商推送
			wxTemplateMsgService.sendPremisesUnshelveTemplateMsg(agencyAccessToken,companyUuid,domain,premisesId,"下架");
		}
	}

	/**
	 * 批量指定分销商单独指定人员
	 * @param premsiesId
	 * @param agentIds
	 * @param agencyAccessToken
	 * @param companyUuid
	 * @param domain
	 */
	@Async
	@Override
	public void sendWeixinMsgWithBatchAssignPremises(Long premsiesId,String agentIds,String agencyAccessToken, String companyUuid, String domain){
		//获取新增分销商和取消分销商
		//获取需要推送微信消息的分销商
		//获取需要推送微信消息的分销商
		Map<String,List<String>> angecy =  getChangeAgency(premsiesId,agentIds);
		wxTemplateMsgService.sendPremisesUnshelveTemplateMsgForAgencyAdmin(agencyAccessToken,companyUuid,domain,  premsiesId.toString(),  angecy.get("cancelAgency"),angecy.get("confirmAgency"));
	}

	@Override
	public SearchCount4CustomerAndPremisesResDto searchCount4CustomerAndPremises(SearchCount4CustomerAndPremisesReqDto reqDto) {
		SearchCount4CustomerAndPremisesResDto resDto = new SearchCount4CustomerAndPremisesResDto();
		if(StringUtils.isBlank(reqDto.getKeyword())){
			resDto.setTotalCount(0);
			resDto.setCustomerCount(0);
			resDto.setPremisesCount(0);
		}
		PremisesDto premisesDto = new PremisesDto();
		premisesDto.setPremisesName(reqDto.getKeyword());
		int premisesCount = premisesMapper.count(premisesDto);
		resDto.setPremisesCount(premisesCount);
		CustomerPremisesDto customerPremisesDto = new CustomerPremisesDto();
		customerPremisesDto.setSearchContent(reqDto.getKeyword());
		customerPremisesDto.setStaffId(reqDto.getStaffId());
		customerPremisesDto.setStaffCompanyId(reqDto.getMerchantId());
		int customerCount = customerPremisesMapper.myCount(customerPremisesDto);
		resDto.setCustomerCount(customerCount);
		resDto.setTotalCount(premisesCount + customerCount);
		resDto.setResult(ResultEnum.SUCCESS.getNo());
		return resDto;
	}

	@Override
	public GetBindPremisesResDto getPremisesListForPartner(GetPartnerBindPremisesReqDto reqDto) {
		PartnerInfo partnerInfo = partnerInfoService.selectById(Long.valueOf(reqDto.getUserId()));
		List<Premises> inPremisesList = new ArrayList<>();
		// 如果是管理员
		if (partnerInfo.getAccountType().equals(MechanismAccountTypeEnum.mechanism.getNo())) {
			PremisesDto dto = new PremisesDto();
			dto.setCompanyId(partnerInfo.getHigherid());
			dto.setPremisesStatus(PremisesStatusEnum.type1.getNo());
			inPremisesList = premisesService.selectIdListByDto(dto);
		}else{
			// 个人驻守ID
			CaseMemberDto caseMemberDto = new CaseMemberDto();
			caseMemberDto.setPartnerId(partnerInfo.getId());
			caseMemberDto.setCompanyId(partnerInfo.getHigherid());
			caseMemberDto.setPremisesStatus(PremisesStatusEnum.type1.getNo());
			List<CaseMember> list = caseMemberService.selectListByDto(caseMemberDto);
			if (CollectionUtils.isNotEmpty(list) ) {
				List<Premises> caseMemberPremisesList = list.stream().map(item -> {
					Premises p = new Premises();
					p.setId(item.getPremisesId());
					p.setName(item.getPremisesName());
					return p;
				}).collect(Collectors.toList());
				inPremisesList.addAll(caseMemberPremisesList);
			}
		}
		PremisesDto premisesDto = new PremisesDto();
		premisesDto.setMobileTemp(partnerInfo.getPhone());
		premisesDto.setCompanyId(partnerInfo.getHigherid());
		premisesDto.setPremisesStatus(PremisesStatusEnum.type1.getNo());
		// 项目经理或者渠道总监
		List<Premises> premisesListForManage = premisesService.selectIdListByMobileTemp(premisesDto);
		if(CollectionUtils.isNotEmpty(premisesListForManage)){
			inPremisesList.addAll(premisesListForManage);
		}

		// 置业顾问关联的楼盘
		List<EstateAdviser> adviserList = estateAdviserService.selectListByPartner(partnerInfo.getId());
		if(CollectionUtils.isNotEmpty(adviserList)){
			List<Long> premisesIds = adviserList.stream().map(EstateAdviser::getPremisesId).collect(Collectors.toList());
			premisesDto = new PremisesDto();
			premisesDto.setPremisesIds(premisesIds);
			premisesDto.setPremisesStatus(PremisesStatusEnum.type1.getNo());
			List<Premises> adviserPremisesList = premisesService.selectIdListByDto(premisesDto);
			inPremisesList.addAll(adviserPremisesList);
		}

		List<PremisesDto> premisesDtoList = new ArrayList<>();
		if(CollectionUtils.isNotEmpty(inPremisesList)){
			for(Premises p : inPremisesList){
				boolean b = premisesDtoList.stream().anyMatch(u -> u.getId().equals(p.getId()));
				if (!b) {
					PremisesDto dto = new PremisesDto();
					BeanUtils.copyProperties(p, dto);
					premisesDtoList.add(dto);
				}
			}
		}
		GetBindPremisesResDto dto = new GetBindPremisesResDto();
		dto.setInPremisesList(premisesDtoList);
		dto.setResult(ResultEnum.SUCCESS.getNo());
		return dto;
	}

	@Override
	public GetBindPremisesResDto getPremisesListBySatus(GetPartnerBindPremisesReqDto reqDto) {
		GetBindPremisesResDto resDto = new GetBindPremisesResDto();
		if (StringUtils.isEmpty(reqDto.getUserId())) {
			resDto.setResult(ResultEnum.FAIL.getNo());
			resDto.setResultMsg("用户id不能为空");
			return resDto;
		}
		PartnerInfo pi = partnerInfoService.selectById(Long.valueOf(reqDto.getUserId()));
		PremisesDto entity = new PremisesDto();
		entity.setCompanyId(pi.getHigherid());
		entity.setPremisesStatus(PremisesStatusEnum.type1.getNo());
		entity.setOrders(" orderStatus, t.create_time desc");
		String premisesStatus = reqDto.getPremisesStatus();

		if (StringUtils.isNotEmpty(premisesStatus)) {
			List<String> list = new ArrayList<>();
			for (String status : premisesStatus.split(",")) {
				list.add(status);
			}
			entity.setListPremisesStatus(list);
		}
		List<Premises> premisesList = premisesService.getListByCaseMember(entity);
		List<PremisesDto> premisesDtoList = new ArrayList<>();
		premisesList.forEach(item -> {
			PremisesDto premisesDto = new PremisesDto();
			BeanUtils.copyProperties(item, premisesDto);
			premisesDtoList.add(premisesDto);
		});
		resDto.setInPremisesList(premisesDtoList);
		return resDto;
	}

	@Override
	public GetAgentPremisesPageResDto getAgentPremisesList(GetAgentPremisesPageReqDto dto) {
		GetAgentPremisesPageResDto resDto = new GetAgentPremisesPageResDto();
		PartnerInfo pi = partnerInfoService.selectById(stringToLong(dto.getUserId()));

		int pageNo = dto.getPageNo();
		int pageSize = dto.getPageSize();

		// 根据公司uuid查询开发商
		CompanyDto cDto = new CompanyDto();
		cDto.setStatus(CheckStatusEnum.SUCCESS.getNo());
		cDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
		cDto.setCompanyUuid(dto.getCompanyUuid());
		Company company = companyService.selectByDto(cDto);

		if (null == company) {
			//此处为商户不存在
			resDto.setResult(ResultEnum.FAIL.getNo());
			resDto.setResultMsg("未获取到开发商信息!");
			return resDto;
		}
		Long companyId = company.getId();
		PremisesDto entity = new PremisesDto();
		// 在楼盘关系表中查询相关楼盘
		PremisesRelationDto relationDto = new PremisesRelationDto();
		relationDto.setDevCompanyId(companyId);
		relationDto.setAgentCompanyId(pi.getHigherid());
		relationDto.setStatus(MechanismStatusEnum.enable.getNo());
		relationDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
		List<PremisesRelation> relation = premisesRelationService.selectListByDto(relationDto);
		if (relation == null) {
			resDto.setResult(ResultEnum.FAIL.getNo());
			resDto.setResultMsg("在楼盘关系表中查询相关楼盘失败!");
			return resDto;
		}
		List<Long> premisesIds = relation.stream().map(PremisesRelation::getPremisesId).collect(Collectors.toList());
		entity.setPremisesIds(premisesIds);

		if (StringUtils.isNotEmpty(dto.getName())) {
			entity.setName(dto.getName());
		}
		if (dto.getProvinceId() != null) {
			entity.setProvinceId(dto.getProvinceId());
		}
		if (dto.getCityId() != null) {
			entity.setCityId(dto.getCityId());
		}
		if (dto.getAreaId() != null) {
			entity.setAreaId(dto.getAreaId());
		}
		entity.setPremisesStatus(PremisesStatusEnum.type1.getNo());
		// 排序规则
		entity.setOrders(" (CASE WHEN tp.main_push = 1 THEN NULL ELSE tp.main_push END) desc, (CASE WHEN tp.sequence IS NULL THEN 1 ELSE 0 END) ASC," +
				"tp.sequence ASC,tp.main_push_settime desc, tp.premises_status asc,tp.create_time desc ");
		// 在售状态
		entity.setSaleStatus(SaleStatusEnum.type_1.getNo());
		Page<ReportInfo> agentPremisesList = premisesService.getAgentPremisesList(entity, PageUtil.begin(pageNo, pageSize), pageSize);
		List<ReportInfo> collect = agentPremisesList.getRows().stream().filter(reportInfo -> {
			String specialTime = reportInfo.getSpecialTime();
			if (specialTime.contains("-")) {
				reportInfo.setSpecialTime("-");
			}
			if (specialTime.contains("小时")) {
				Long aLong = Long.valueOf(specialTime.substring(0, specialTime.length() - 2));
				String s = aLong / 60 + "小时";
				reportInfo.setSpecialTime(s);
			}
			if (specialTime.contains("天")) {
				Long aLong = Long.valueOf(specialTime.substring(0, specialTime.length() - 1));
				String s = aLong / 1440 + "天";
				reportInfo.setSpecialTime(s);
			}
			return true;
		}).collect(Collectors.toList());
		agentPremisesList.setRows(collect);
		agentPremisesList.setPageSize(pageSize);
		agentPremisesList.setPageNumber(pageNo);
		resDto.setGetAgentPremisesList(agentPremisesList);
		resDto.setResult(ResultEnum.SUCCESS.getNo());
		return resDto;
	}
	
	/**
	 * 楼盘关注、公司ID，楼盘ID，以及对应的楼盘所在公司ID是否正确
	 * @param premisesAttetionDto
	 * @return
	 */
	@Transactional
	public String updatePremisesPartnerRel(PremisesPartnerDto premisesPartnerDto) {
		
		//判断员工和公司所对应的信息是否正常
		PartnerInfoDto partnerInfoDto = new PartnerInfoDto();
		partnerInfoDto.setId(premisesPartnerDto.getPartnerId());
		partnerInfoDto.setHigherid(premisesPartnerDto.getPartnerCompanyId());
		partnerInfoDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
		if (partnerInfoService.selectByDto(partnerInfoDto) == null) {
			logger.info("员工信息有误，输入员工ID：" + premisesPartnerDto.getPartnerId()
				+ "员工对应公司" + premisesPartnerDto.getPartnerCompanyId());
			return "输入参数有误";
		}
		
		//判断楼盘和所对应的公司是否正常
		PremisesDto premisesDto = new PremisesDto();
		premisesDto.setId(premisesPartnerDto.getPremisesId());
		premisesDto.setCompanyId(premisesPartnerDto.getPremisesCompanyId());
		premisesDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
		if (premisesService.selectByDto(premisesDto) == null) {
			logger.info("楼盘信息有误，输入楼盘ID：" + premisesPartnerDto.getPremisesId()
				+ "楼盘对应公司" + premisesPartnerDto.getPremisesCompanyId());
			return "输入参数有误";
		}
		
		// 兼容老版本的逻辑，当时使用的attetion_status 字段，而不是 relType，relFlag
		Integer attetionFlag = premisesPartnerDto.getAttentionFlag();
		if(attetionFlag != null) {
			premisesPartnerDto.setRelFlag(attetionFlag);
			premisesPartnerDto.setRelType(RelTypeEnum.attention.getNo());
		}
		
		Long premisesId = premisesPartnerDto.getPremisesId();
		int relFlag = premisesPartnerDto.getRelFlag();
		// 如果是店铺，则查询所有楼盘
		if(RelTypeEnum.shop.getNo() == premisesPartnerDto.getRelType()) {
			premisesPartnerDto.setPremisesId(null);
		}
		premisesPartnerDto.setRelFlag(null);
		// 查出当前人员的所有（关注/未关注）或者（收藏/未收藏）的数据
		List<PremisesPartner> premisesPartners = premisesPartnerService.selectListByDto(premisesPartnerDto);
		premisesPartnerDto.setPremisesId(premisesId);
		premisesPartnerDto.setRelFlag(relFlag);
		
		//获取对应状态的数据
		String judgeResult = judgeUpdate(premisesPartnerDto, premisesPartners);
		if(judgeResult.contains("失败")) {
			return judgeResult;
		}
		
		// 判断是新增还是修改。 如果存在当前楼盘对应的状态数据，则是新增，否则是修改
		if(RelTypeEnum.shop.getNo() == premisesPartnerDto.getRelType()) {
			premisesPartners = premisesPartners.stream().filter(premisesPartner -> {
				return premisesId.longValue() == premisesPartner.getPremisesId().longValue();
			}).collect(Collectors.toList());
		}
		
		//判断是否要更新
		if (premisesPartners == null || premisesPartners.size() == 0) {
			premisesPartnerDto.setCreateTime(new Date());
			premisesPartnerDto.setUpdateTime(new Date());
			premisesPartnerDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
			premisesPartnerService.create(premisesPartnerDto);
			return "插入成功";
		}
		premisesPartnerDto.setId(premisesPartners.get(0).getId());
		premisesPartnerService.update(premisesPartnerDto);
		return "更新成功";
	}

	/**
	 * 判断是否更新
	 * @return
	 */
	private String judgeUpdate(PremisesPartnerDto premisesAttetionDto, List<PremisesPartner> premisesPartners) {
		if(!judgeShopNumber(premisesAttetionDto, premisesPartners)) {
			return "收藏失败，最多收藏十个店铺";
		}
		return "成功";
	}
	
	/**
	 * 判断收藏的店铺数量,最多10个
	 * @param premisesAttetionDto
	 * @return
	 */
	private boolean judgeShopNumber(PremisesPartnerDto premisesPartnerDto, List<PremisesPartner> premisesPartners) {
		boolean addShopFlag = AttetionStatusEnum.set_attetion.getNo() == premisesPartnerDto.getRelFlag()
				&& RelTypeEnum.shop.getNo() == premisesPartnerDto.getRelType();
		if(!addShopFlag) return true;
		
		// 判断收藏的数据有多少
		int shopNumber = 0;
		for (PremisesPartner premisesPartner : premisesPartners) {
			if(AttetionStatusEnum.set_attetion.getNo() == premisesPartner.getRelFlag()) {
				shopNumber ++;
			}
		}
		
		if(shopNumber < 10) {
			return true;
		}
		return false;
	}

	public static void main(String[] args) {
		List<String> haha = new ArrayList<>();
		haha.add("1");
		haha.add("11");
		haha.add("111");
		haha.add("1111");
		haha.add("11111");
		System.out.println(String.join(",", haha));
	}
}
